Reputation: 8362
I've written this code in order to fetch items from multiple url's . I want to know when all of the $.get
calls have been satisfied :
foo : function(arrIds){
var arrJqxhr = [];
var arrReturnedData = []
for ( var i = 0, l = arrIds.length; i < l; i++ ) {
var url = '/thing/' + arrIds[i].toString()
arrJqxhr[i] = $.get(url)
.done(function(data, textStatus, jqXHR) {
arrReturnedData.push(data);
})
}
Apart from keeping count of how many times the .done
has been called is there any better way ?
Upvotes: 0
Views: 26
Reputation: 388316
You can use $.when
var arrReturnedData = [];
var arrJqxhr = $.map(arrIds, function (id) {
var url = '/thing/' + id.toString()
return $.get(url)
.done(function (data, textStatus, jqXHR) {
arrReturnedData.push(data);
})
});
$.when.apply($, arrJqxhr).then(function(){
//this will be called once all requests are successfully completed
$.each(arguments, function(i, arr){
arrReturnedData.push(arr[0])
});
});
Upvotes: 1