2017-02-07 134 views
4

我對$q的工作方式非常熟悉,我在angularjs中使用它來等待單個承諾解決和多個承諾以$q.all()來解決。

問題是我不確定它是否有可能做到這一點(以及它是否正常工作):我可以等待一個承諾解決,但也可以運行一些代碼,當我所有的承諾解決了。之後的個人承諾的成功回調已經完成...例如:

var promises = []; 
for(i=1, i<5, i++){ 
    var singlePromise = SomeSevice.getData(); 
    promises.push(singlePromise); 
    singlePromise.then(function(data){ 
     console.log("This specific promise resolved"); 
    }); 
} 


// note: its important that this runs AFTER the code inside the success 
// callback of the single promise runs .... 
$q.all(promises).then(function(data){ 
    console.log("ALL PROMISES NOW RESOLVED"); // this code runs when all promises also resolved 
}); 

我的問題是,這是否工作,因爲我覺得是這樣,還是有一些奇怪的異步,非確定性結果的風險?

+0

嗨@lonesomeday,我對我的問題做了一個小改動;主要的要求是all()回調在單個promise的成功回調完成後運行! – rex

+0

我看到了,並刪除了我的評論,因爲它不再相關。 – lonesomeday

+0

因此,你的問題實際上是否在最後的'singlePromise.then'回調之後,'.all'回調總是被觸發**? – devqon

回答

5

致電then也返回承諾。然後你可以將它傳遞給你的數組,而不是原來的承諾。這樣,您的$q.all將在所有then已執行後運行。

var promises = []; 
for(i=1, i<5, i++){ 
    // singlePromise - this is now a new promise from the resulting then 
    var singlePromise = SomeSevice.getData().then(function(data){ 
     console.log("This specific promise resolved"); 
    }); 
    promises.push(singlePromise); 
} 

$q.all(promises).then(function(data){ 
    console.log("ALL PROMISES NOW RESOLVED"); 
}); 
+1

這聽起來很棒 - 我會試試看。 – rex

+2

如果一個promise失敗,所有的鏈接都會停止,但是如果你放在個人承諾中,鏈接承諾繼續,並且每個承諾和catch都會在promise.all的數組索引中返回undefined。 –

+0

@RafaelDantas - 好點。並不是我沒有考慮這個問題,但更多的是我覺得這個問題超出了範圍。 OP應該在最終代碼中考慮它,以確保代碼具有容錯性。 – Igor