等待 1 个承诺,然后所有承诺都使用 $q
Wait for 1 promise and then all promises using $q
我相当熟悉 $q
的工作原理,我在 angularjs 中使用它来等待单个承诺解决和多个承诺解决 $q.all()
。
问题是我不确定是否可以这样做(以及它是否正常工作):我可以等待一个单一的承诺来解决,但是当我所有的时候也 运行 一些代码promises 也解决了......在各个 promises 的成功回调完成之后......例如:
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
的调用也是 returns 一个承诺。然后你可以将它传递给你的数组而不是原来的承诺。这样,在执行完所有 then
后,您的 $q.all
将 运行。
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");
});
我相当熟悉 $q
的工作原理,我在 angularjs 中使用它来等待单个承诺解决和多个承诺解决 $q.all()
。
问题是我不确定是否可以这样做(以及它是否正常工作):我可以等待一个单一的承诺来解决,但是当我所有的时候也 运行 一些代码promises 也解决了......在各个 promises 的成功回调完成之后......例如:
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
的调用也是 returns 一个承诺。然后你可以将它传递给你的数组而不是原来的承诺。这样,在执行完所有 then
后,您的 $q.all
将 运行。
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");
});