承诺链接。等待最后的承诺解决

时间:2014-01-31 11:56:29

标签: javascript angularjs promise

我有两个功能:

    getDocument: function(title){

    var defer = $q.defer();

    $timeout(function(){

        defer.resolve(true);            
        console.log(1);

    },2000);

    return defer.promise;
},

anotherFunc : function(){

    var defer = $q.defer();

    console.log(2);
    defer.resolve(document);

    return defer.promise;

}

和电话:

    when('/entry/:title', {templateUrl: 'partials/views/entry.php', controller: 'entryCtrl',resolve: {

    document: function($q,$route,$log,document){

        var defer = $q.defer();

        document.getDocument()
            .then(document.anotherFunc());               

        return defer.promise;
    }
}}).

虽然我已经对getDocument()应用了超时,但anotherFunc()已被调用,即使尚未解决此承诺。

为什么会这样?

我该如何避免这种行为?

1 个答案:

答案 0 :(得分:4)

  

另一个函数被调用,即使诺言尚未解决。

因为您已调用

… document.anotherFunc() …
                      ^^

相反,您希望将函数传递给then(),这将在promise解析时被调用:

….then(document.anotherFunc)

// or, more explicit and preserving 'this':
….then(function(promiseResult) {
    document.anotherFunc();
})
相关问题