SyntaxStudy
Sign Up
jQuery $.when() with Dynamic Arrays
jQuery Advanced 5 min read

$.when() with Dynamic Arrays

$.when() with Arrays

Pass a dynamic array of promises to $.when() using Function.prototype.apply or the spread operator.

Example
const ids = [1, 2, 3, 4, 5];
const requests = ids.map(id => $.getJSON("/api/user/" + id));

// Using apply (jQuery 2.x compatible)
$.when.apply($, requests).done(function() {
  // arguments: [userData1], [userData2], ...
  const users = $.makeArray(arguments).map(a => a[0]);
  renderUsers(users);
});

// Using spread (modern)
$.when(...requests).done((...results) => {
  const users = results.map(r => r[0]);
  renderUsers(users);
});
Pro Tip

With multiple requests, each argument to done() is an array [data, status, jqXHR].