When waiting for multiple deferred objects to plete, why does:
$.when(tasks).then(function() {
document.write("Completed all requests." + "<br/>");
});
execute immediately, yet
$.when.apply(null, tasks).then(function () {
document.write("Completed all requests." + "<br/>");
});
waits until the tasks have pleted.
When waiting for multiple deferred objects to plete, why does:
$.when(tasks).then(function() {
document.write("Completed all requests." + "<br/>");
});
execute immediately, yet
$.when.apply(null, tasks).then(function () {
document.write("Completed all requests." + "<br/>");
});
waits until the tasks have pleted.
Share Improve this question edited Jan 29, 2013 at 1:52 Joseph Silber 220k59 gold badges368 silver badges292 bronze badges asked Jan 29, 2013 at 1:46 Ben FosterBen Foster 34.8k41 gold badges180 silver badges290 bronze badges1 Answer
Reset to default 12The when
function does not take an array of deferreds. Rather, you pass each deferred as a separate argument. That's exactly what apply
is doing for you.
The null
being passed to apply
is just because that's what apply
expects: the first argument is what the context of the function should be set to when its called, and the second argument is always an array, which will be expanded so that the function will be called as if all the items in the array have been passed in as separate arguments.
Since for the purpose of when
it makes no difference what context it's being called with, null
works just as well as anything else. I prefer to pass it jQuery itself:
$.when.apply($, tasks).then(function () {
// Whatever
});
since I think it looks cleaner, but that's just me. It makes no difference whatsoever.
If your browser supports native promises (or you're using a polyfill) you can use its all
method instead, which takes an array of promises directly:
Promise.all(tasks).then(function (values) {
// "values" is an array, with the results of each of the "tasks"
});