The traditional way:
The traditional way to solve this is to add the promises to an array, then evaluate them all together using $.when.apply
var promise = [];
for (var i = 0; i < 6; i++){
promise.push(delay(10-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
alert("All done");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/rgj0bx95/1/
Working with returned values:
As you want to keep the values, you can then access them using the arguments
array:
var promise = [];
for (var i = 0; i < 6; i++){
promise.push(delay(6-i, $('#' + i)));
}
$.when.apply($, promise).done(function(){
$('body').append("All done!");
for (var i = 0; i < arguments.length; i++){
$('body').append(arguments[i]).append("<br/>");
}
});
Example:
The following example uses a simple function that returns a promise, using a timer, to simulate ajax calls. It clearly shows the suggestion working even though the promises complete in "random" order (just to demonstrate):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/rgj0bx95/5/
Notes:
- The values are returned in the order the calls were made, not the completion order.
Other methods
Little trick I found: You can chain promises in parallel with $.when
without having to use an array of promises:
var promise; // Undefined also means a resolved promise to $.when
for(...){//we don't know the number of ajax calls
promise = $.when(promise, $.ajax({...}));
}
promise.done(function(){
alert("All done");
});
Notes:
- I figured this one out after seeing someone chain promises sequentially, using
promise = promise.then(newpromise)
- The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested recursively inside additional objects). If you do not require the parameters, it is short and simple.
You will note in the following fiddle that the results are nested and in the reverse order you want them. Again this technique is only useful if you do not want the results of the promises (which is quite often for parallel operations).
Summary: The $.when
technique is only useful if you do not care about the result values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/rgj0bx95/9/