rex rex - 1 year ago 76
AngularJS Question

Wait for 1 promise and then all promises using $q

I'm fairly familiar with how

$q
works and I use it in angularjs to wait for single promises to resolve and multiple promises to resolve with
$q.all()
.

The question is I'm not sure if its possible to do this (and if it works correctly): Can I wait for a single promise to resolve, but then also run some code when all my promises resolve too... AFTER the success callbacks of the individual promises have finished... for example:

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
});


My question is, does this work as I think it does, or is there some weird async, indeterministic result risk?

Answer Source

A call to then also returns a promise. You can then pass this to your array instead of the original promise. This way your $q.all will run after all your thens have been executed.

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");
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download