I want to make three ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The calls themselves ar
It's worth noting that since $.when expects all of the ajax requests as sequential arguments (not an array) you'll commonly see $.when used with .apply() like so:
// Save all requests in an array of jqXHR objects
var requests = arrayOfThings.map(function(thing) {
return $.ajax({
method: 'GET',
url: 'thing/' + thing.id
});
});
$.when.apply(this, requests).then(function(resp1, resp2/*, ... */) {
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var responseArgsArray = Array.prototype.slice.call(this, arguments);
});
Using the Spread syntax, you can now write this code like so:
$.when(...requests).then((...responses) => {
// do something with responses
})
This is because $.when accepts args like this
$.when(ajaxRequest1, ajaxRequest2, ajaxRequest3);
And not like this:
$.when([ajaxRequest1, ajaxRequest2, ajaxRequest3]);