Ben Foster Ben Foster - 1 year ago 91
jQuery Question

Waiting for multiple deferred objects to complete

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.

Answer Source

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