When waiting for multiple deferred objects to complete, 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 completed.
The
whenfunction does not take an array of deferreds. Rather, you pass each deferred as a separate argument. That’s exactly whatapplyis doing for you.The
nullbeing passed toapplyis just because that’s whatapplyexpects: 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
whenit makes no difference what context it’s being called with,nullworks just as well as anything else. I prefer to pass it jQuery itself: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
allmethod instead, which takes an array of promises directly: