2016-08-08 39 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它会执行自身的引用。