我非常熟悉$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 :(得分:6)
对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");
});