[英]Order promises execution in AngularJs
我正在使用ES6和babel处理Angular全栈。
在我的控制器中,我有:
$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()});
似乎工作但似乎不是一个干净的解决方案。
你应该传递函数引用,如.then(aFunction)
而不是函数调用。 目前你正在做aFunction()
立即调用该函数。
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction)
}
aFunction
立即执行,其结果传递给.then()
。
它应该是: .then(aFunction)
这将传递对它将自己执行的.then
的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.