我非常熟悉 $q
的工作原理,我在 angularjs 中使用它来等待单个 promise 的解决和多个 promise 的解决 $q.all()
.
问题是我不确定是否可以这样做(以及它是否正常工作):我可以等待一个单一的 promise 解决,然后在我所有的 promise 都解决时运行一些代码......在各个 promise 的成功回调完成后...例如:
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
});
我的问题是,这是否像我想的那样工作,或者是否存在一些奇怪的异步、不确定的结果风险?
最佳答案
调用 then
也会返回一个 promise 。然后你可以将它传递给你的数组而不是原来的 promise 。这样你的 $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");
});
关于javascript - 等待 1 个 promise ,然后所有 promise 都使用 $q,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42091078/