Pass an Array of Deferreds to $.when()
When dealing with a complex set of asynchronous tasks, it can be convenient to pass an array of Deferred objects to the $.when() method to notify when all the tasks have completed. However, by default, $.when() expects separate Deferred objects as individual parameters, which can be impractical if the number of Deferred objects is unknown. This article provides a solution to this issue using Function.prototype.apply.
Solution:
To pass an array of Deferred objects to $.when(), use the Function.prototype.apply method as follows:
$.when.apply($, my_array).then( ___ );
This allows you to pass an array of Deferred objects as a single argument to $.when(). The example code below demonstrates this approach:
var deferreds = getSomeDeferredStuff(); $.when.apply($, deferreds).done(function() { $("div").append("<p>All done!</p>"); });
ES6:
In ES6, you can use the spread operator (...) instead of Function.prototype.apply:
$.when(...my_array).then( ___ );
Note:
It's important to note that the handler function provided to the .then() method should process the arguments array to retrieve the result of each promise. Since the number of formal parameters the handler will require is likely unknown in advance, the handler must accordingly process the arguments array.
The above is the detailed content of How Can I Pass an Array of Deferred Objects to jQuery's `$.when()`?. For more information, please follow other related articles on the PHP Chinese website!