2017-02-07 36 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