Reputation: 6115
I want to generate ajax requests on the fly, but I want to make sure I get a callback after they have all completed, so I want to wrap them within a .when .done statement like the following:
$.when(function(){
$.each(oOptions, function(){
var filePath = this.filePath,
dataType = this.dataType;
$.ajax({
url : filePath,
dataType : dataType
});
});
})
.done(function(){
console.log('success');
console.log(arguments);
})
.fail(function(){
console.log('failed');
});
where my options is an array of objects containing the filepath and datatype for each ajax request I want to make simultaneously. this code will return success, but the arguments is just a function, and the ajax requests never go through. any thoughts on how to do this?
Upvotes: 1
Views: 380
Reputation: 154838
You pass a function to $.when
, while you should pass one or more Deferred
s. You could fill an array with deferreds and pass that to $.when
as arguments:
var deferreds = [];
$.each(oOptions, function() {
var filePath = this.filePath,
dataType = this.dataType;
deferreds.push($.ajax({
url : filePath,
dataType : dataType
}));
});
// use the array elements as arguments using apply
$.when.apply($, deferreds)
.done(function(){
console.log('success');
console.log(arguments);
})
.fail(function(){
console.log('failed');
});
Upvotes: 1
Reputation: 1032
Don't you have to put the "done" logic into the $.ajax call arguments as the success function? I mean something like this:
$.ajax({
url : filePath,
dataType : dataType,
success: function(){
console.log('success');
}
});
Since the ajax calls are made asynchronously, the done() could be called before the ajax calls have completed...
Upvotes: 1