$.when() with Arrays
Pass a dynamic array of promises to $.when() using Function.prototype.apply or the spread operator.
Pass a dynamic array of promises to $.when() using Function.prototype.apply or the spread operator.
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);
});
With multiple requests, each argument to done() is an array [data, status, jqXHR].