订单承诺在 AngularJs 内执行
Order promises execution in AngularJs
我正在研究 Angular 使用 ES6 和 babel 的全栈。
在我的控制器中,我有:
$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()});
似乎可行,但似乎不是一个干净的解决方案。
aFunction
立即执行并将其结果传递给 .then()
。
应该是:.then(aFunction)
这将传递对 .then
的引用,它将自行执行。
您应该像 .then(aFunction)
一样传递函数引用而不是函数调用。当前您正在做的 aFunction()
是立即调用该函数。
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction)
}
我正在研究 Angular 使用 ES6 和 babel 的全栈。
在我的控制器中,我有:
$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()});
似乎可行,但似乎不是一个干净的解决方案。
aFunction
立即执行并将其结果传递给 .then()
。
应该是:.then(aFunction)
这将传递对 .then
的引用,它将自行执行。
您应该像 .then(aFunction)
一样传递函数引用而不是函数调用。当前您正在做的 aFunction()
是立即调用该函数。
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction)
}