Reputation: 608
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?
Upvotes: 4
Views: 1581
Reputation: 1075537
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
});
Upvotes: 3
Reputation: 767
From the jQuery documentation :
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then( myFunc, myFailure );
Execute the function myFunc
when both ajax requests are successful, or myFailure
if either one has an error.
So you can use this system to send variable number of requests and still have the same callback functions :)
Adapted with @TW80000 answer :
var requests = [];
....
$.when.apply($, requests ).done( myFunc, myFailure );
Upvotes: 0
Reputation: 1515
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.
});
Upvotes: 6