【问题标题】:Order promises execution in AngularJs订单承诺在 AngularJs 中执行
【发布时间】:2016-12-14 10:11:10
【问题描述】:

我正在使用 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()}); 似乎有效,但似乎不是一个干净的解决方案。

【问题讨论】:

    标签: javascript angularjs promise ecmascript-6 es6-promise


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      aFunction 立即执行,其结果传递到.then()

      应该是:.then(aFunction)

      这将传递对.then 的引用,它将自行执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 2015-05-12
        • 1970-01-01
        • 2017-08-11
        • 2012-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多