Home >Web Front-end >JS Tutorial >How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?

How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 20:54:16857browse

How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?

Handling Arrays of Deferreds in $.when()

When working with arrays of Deferred promises, it's important to know how to handle them when passing them into $.when(). In this article, we will delve into an issue where an array of Deferreds is not handled correctly by $.when() and provide a solution.

The Problem

Consider the following code:

function getSomeDeferredStuff() {
  var deferreds = [];

  for (i = 1; i <= 10; i++) {
    var count = i;

    deferreds.push(
      $.post('/echo/html/', {
        html: '<p>Task #' + count + ' complete.',
        delay: count
      }).success(function(data) {
        $("div").append(data);
      }));
  }

  return deferreds;
}

$(function() {
  $("a").click(function() {
    var deferreds = getSomeDeferredStuff();

    $.when(deferreds).done(function() {
      $("div").append('<p>All done!</p>');
    });
  });
});

In this example, "All done!" should appear after all deferred tasks have completed. However, $.when() doesn't recognize the array of Deferreds as a single entity, resulting in "All done!" being displayed prematurely.

The Solution

To pass an array of Deferreds to $.when(), use Function.prototype.apply:

$.when.apply($, my_array).then( ___ );

This function takes an array of parameters and applies them to a function. For example:

$.when.apply($, deferreds).then(function() {
  $("div").append('<p>All done!</p>');
});

Alternatively, in ES6 you can use the spread operator:

$.when(...my_array).then( ___ );

The above is the detailed content of How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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