等待1个承诺然后使用$ q进行所有承诺

rex*_*rex 4 javascript asynchronous angularjs q angular-promise

我非常熟悉如何$q工作,我在angularjs中使用它等待单个promises解决和多个promise来解决$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
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,这是否像我认为的那样有效,或者是否存在一些奇怪的异步,不确定的结果风险?

Igo*_*gor 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");
});
Run Code Online (Sandbox Code Playgroud)

  • 如果一个promise失败,所有的链承诺都会停止,但如果你把catch放在个人的promise中,那么chain promise就会继续,并且每个带catch的promise都会在promise.all的数组索引中返回undefined. (2认同)