Home > Web Front-end > JS Tutorial > How Can I Pass an Array of Deferred Objects to jQuery's `$.when()`?

How Can I Pass an Array of Deferred Objects to jQuery's `$.when()`?

Mary-Kate Olsen
Release: 2024-12-09 21:57:13
Original
639 people have browsed it

How Can I Pass an Array of Deferred Objects to jQuery's `$.when()`?

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( ___ );
Copy after login

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>");
});
Copy after login

ES6:

In ES6, you can use the spread operator (...) instead of Function.prototype.apply:

$.when(...my_array).then( ___ );
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template