簡體   English   中英

承諾鏈。 等待最后的諾言解決

[英]Promise chaining. Wait for last promise to resolve

我有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() get。

為什么是這樣?

我如何避免這種行為?

即使尚未解決承諾,也會調用anotherFunc()獲取。

因為您已經調用它:

… document.anotherFunc() …
                      ^^

相反,您想將一個函數傳遞給then() ,當promise解析時將調用該函數:

….then(document.anotherFunc)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM