Here's an contrived example of what's going on: http://jsfiddle.net/adamjford/YNGcm/20/
HTML:
<a href="#">Click me!</a>
<div></div>
JavaScript:
function getSomeDeferredStuff() {
var deferreds = [];
var i = 1;
for (i = 1; i <= 10; i++) {
var count = i;
deferreds.push(
$.post('/echo/html/', {
html: "<p>Task #" + count + " complete.",
delay: count
}).success(function(data) {
$("div").append(data);
}));
}
return deferreds;
}
$(function() {
$("a").click(function() {
var deferreds = getSomeDeferredStuff();
$.when(deferreds).done(function() {
$("div").append("<p>All done!</p>");
});
});
});
I want "All done!" to appear after all of the deferred tasks have completed, but $.when()
doesn't appear to know how to handle an array of Deferred objects. "All done!" is happening first because the array is not a Deferred object, so jQuery goes ahead and assumes it's just done.
I know one could pass the objects into the function like $.when(deferred1, deferred2, ..., deferredX)
but it's unknown how many Deferred objects there will be at execution in the actual problem I'm trying to solve.
As a simple alternative, that does not require
$.when.apply
or anarray
, you can use the following pattern to generate a single promise for multiple parallel promises:e.g.
Notes:
promise = promise.then(newpromise)
You can apply the
when
method to your array:How do you work with an array of jQuery Deferreds?
When calling multiple parallel AJAX calls, you have two options for handling the respective responses.
Promises'
array and$.when
which acceptspromise
s and its callback.done
gets called when all thepromise
s are return successfully with respective responses.Example