Reputation: 1864
So, based off of this tutorial on Medium (https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f#.d7ymg99mp), I am trying to use deferred arrays, ajax requests and jQuery.when method to make multiple ajax requests and obtain the result from each one of them.
Here is the code for what I am doing
function updateAllGoingButtons(){
var dataToPass = {};
var deferreds = [];
$('.btn-group').find('button').each(function(){
console.log($(this).attr('id'));
dataToPass.button = $(this).attr('id');
var ajax = $.ajax({
url: '/update-buttons',
method: 'post',
data: dataToPass,
dataType:'json'
});
deferreds.push(ajax);
$.when.apply($, deferreds).then(function(){
});
});
}
My confusion arises as to how to use this $.when function and where I can access the data returned to the ajax call.
I tried inserting a simple success option, but that didn't enter its callback function. How do I do this?
Upvotes: 2
Views: 78
Reputation: 1075209
You're just calling when
too soon. Do it outside the each
loop, after you've started all your ajax calls and gotten their promises in the array:
function updateAllGoingButtons(){
var dataToPass = {};
var deferreds = [];
$('.btn-group').find('button').each(function(){
console.log($(this).attr('id'));
dataToPass.button = $(this).attr('id');
var ajax = $.ajax({
url: '/update-buttons',
method: 'post',
data: dataToPass,
dataType:'json'
});
deferreds.push(ajax);
});
$.when.apply($, deferreds).then(function(){ // <=== Moved this
// <===
}); // <===
}
The results of those ajax calls will be provided to your then
function as a series of discrete arguments. Each argument will be an array with three entries, corresponding to the three arguments normally passed to success
functions. Since you're dealing with an array, you'll probably want to access them via the arguments
pseudo-array. It's also always a good idea to have a rejection handler (the second argument to then
, or alternately use catch
with recent versions of jQuery):
$.when.apply($, deferreds).then(
function() {
var n;
for (n = 0; n < arguments.length; ++n) {
console.log("Result " + n, arguments[n][0]);
}
},
function() {
// At least one request failed
}
);
Upvotes: 2