2014-01-31 143 views
0

我有2个功能:承诺链接。等待最后的承诺,以解决

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()获取的叫,承诺有没有当连尚未解决。

这是为什么?

我该如何避免这种行为?

+0

你有一些错别字,document.getDocument()。then(document.anotherFunc); 你实际上在你的代码中调用了document.anotherFunc,你没有将它作为参数传递给then函数。 – TestersGonnaTest

+0

@TestertersGonnaTest 谢谢,修正。这不是真正的代码的一部分,只是一个问题,由于重构SO – user2422960

回答

4

anotherFunc()被调用,即使promise尚未解析。

因为你已经称为它:

… document.anotherFunc() … 
         ^^ 

相反,你想给一个函数传递到then()将调用时承诺解决:

….then(document.anotherFunc) 

// or, more explicit and preserving 'this': 
….then(function(promiseResult) { 
    document.anotherFunc(); 
}) 
+0

我欠你一个,谢谢。 – user2422960