Jul*_*ige 2 javascript promise angularjs ecmascript-6 es6-promise
我正在使用ES6和babel处理Angular全栈.
在我的控制器中,我有:
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(() => {console.log("task2")})
}
Run Code Online (Sandbox Code Playgroud)
控制台结果是我想要的:
task1
task2
Run Code Online (Sandbox Code Playgroud)
但是当我尝试重构我的代码时:
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction())
}
aFunction() {
console.log("task2")
}
Run Code Online (Sandbox Code Playgroud)
控制台结果是:
task2
task1
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
Nb:.then(() => {this.aFunction()});似乎工作但似乎不是一个干净的解决方案.
你应该传递函数引用.then(aFunction)而不是函数调用.目前你正在做的aFunction()是立即调用该函数.
$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |