I'm sending multiple ajax requests and want to get a callback if all the requests are successful. I've found $.when($.ajax(), [...]).then(function(results){},[...]);
but that only works when you know in advance how many you're going to do. In my case, it varies depending on user input.
I tried the following but I'm not sure where or how $.when
fits in:
$.when(
$('#piecesTable tr').not(':first').each(function(){
// ...some prep...
$.ajax({
// ...args here...
});
})
).then(function() {
// All requests are done
});
How do I use the results of all those separate $.ajax
calls with $.when
? Or do I handle this some other way?
I think the general structure of what you're looking for is something like this:
var requests = [];
// Populate requests array with ajax requests.
requests.push($.ajax({
// ...
}));
// Add as many requests as you want to the array.
$.when.apply($, requests).done(function() {
var args = $.prototype.slice.call(arguments);
// args should contain the results of your ajax requests.
// Do whatever with the results.
});
There's a modern alternative to the $.when.apply($, arrayOfPromises)
beast: Promise.all
:
Promise.all(arrayOfPromises).then(function(arrayOfResults) {
// Use arrayOfResults
});
Promise.all
expects an array of thenables and returns a promise that resolves with an array of the results when all of the thenables have resolved. It's fine with jQuery's promises, because all it requires is that they be thenables, which they are.
You can use this on any browser with Promise
support, or if you include a Promise
shim/polyfill.
So in your case, you'd build the array:
var arrayOfPromises = [];
$('#piecesTable tr').not(':first').each(function(){
// ...some prep...
arrayOfPromises.push($.ajax({ // ** Push this promise into the array
// ...args here...
}));
});
(Or you can build it with $.map
or Array#map
.)
And then use the array:
Promise.all(arrayOfPromises).then(function(arrayOfResults) {
// Use arrayOfResults
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With