javascript - 订单 promise 在 AngularJs 中执行

标签 javascript angularjs promise ecmascript-6 es6-promise

我正在使用 ES6 和 babel 开发 Angular 全栈。

在我的 Controller 中,我有:

$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()}); 似乎可行,但似乎不是一个干净的解决方案。

最佳答案

您应该传递像 .then(aFunction) 这样的函数引用,而不是函数调用。当前您正在执行的 aFunction() 会立即调用该函数。

$onInit() { 
    this.$http.get('/api/example')
        .then(() => {console.log("task1")})
        .then(aFunction)
}

关于javascript - 订单 promise 在 AngularJs 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832522/

相关文章:

Javascript 在执行 2 个函数后失败,即使函数相同

JavaScript setInterval 只运行一次

javascript - CSS - 在文本中滑动

javascript - 我如何在 node.js 中使用 promises 来清理回调链?

angularjs - 在 Angular 中,promise 的 error 和 catch 函数在概念上的区别是什么?

javascript - 写 Action 和 reducer 高效且干净(react redux)

javascript - Sequelize.js 查询通过关系获取总数

angularjs - 输入自动对焦属性

javascript - 仅当外部更改时才触发 $watch

JavaScript/React - 在函数内返回 Promise