2016-08-08 38 views
2

我正在使用ES6和babel的Angular全堆棧。訂單承諾在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 

爲什麼會發生這種情況?

鈮:.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它會執行自身的引用。