2016-08-08 3 views
2

저는 ES6과 babel을 사용한 Angular full-stack 작업을하고 있습니다.AngularJs에서 명령 실행을 약속합니다.

$onInit() { 
    this.$http.get('/api/example') 
     .then(() => {console.log("task1")}) 
     .then(() => {console.log("task2")}) 
} 

콘솔 결과가 내가 원하는 무엇인가 : 내 컨트롤러에서

, 내가 가진

task1 
task2 

하지만 내 코드를 리팩토링 할 때 :

$onInit() { 
    this.$http.get('/api/example') 
     .then(() => {console.log("task1")}) 
     .then(aFunction()) 
} 

aFunction() { 
    console.log("task2") 
} 

콘솔 결과 :

task2 
task1 

왜 이런 일이 발생합니까?

Nb : .then(() => {this.aFunction()});은 효과가 있지만 깨끗한 해결책으로 보이지 않습니다.

답변

6

함수 호출 대신 .then(aFunction)과 같은 함수 참조를 전달해야합니다. 현재 aFunction()이 바로 그 기능을 호출하고 있습니다.

$onInit() { 
    this.$http.get('/api/example') 
     .then(() => {console.log("task1")}) 
     .then(aFunction) 
} 
4

aFunction이 즉시 실행되고 결과는 .then()으로 전달됩니다.

그것은 같아야 .then(aFunction)

이것은 그 자체를 수행 할 .then에 대한 참조를 전달한다.

관련 문제