I have a for loop statement, each loop will execute an ajax call.
$.each(arr, function(i, v) {
var url = \'/xml.php?id=\' + v;
$.ajax({
url:
Try using $.when()
var arr = [];
$.each(arr, function(i, v) {
var url = '/xml.php?id=' + v;
var xhr = $.ajax({
url: url,
type: 'GET',
dataType: 'xml',
success: function(xml) {
if ($(xml).find('Lists').attr('total') == 1) {
// some code here
}
},
complete: function() {
// some code here
}
});
arr.push(xhr);
})
$.when.apply($, arr).then(function(){
console.log('do')
})
I came across a similar scenario but inside the loop, the AJAX call was done in another function call (called fetchData).
so I made the fetchData function return a Promise coming from the AJAX call and I chained it using the then clause in order to process the response.
Here's the Plunker link
$(document).ready(function() {
var message = '';
process();
function process() {
var promises = [];
for (var i = 0; i < 3; i++) {
var promise;
(function (index) {
promise = fetchData(index).then(function (response) {
// do something with the response.
message += 'Iteration ' + index + '\n';
});
})(i);
promises.push(promise);
}
$.when.apply($, promises).then(function () {
// do something after all the AJAX calls are completed.
alert(message);
});
}
function fetchData(param) {
return $.ajax('data.json')
.success(fetchDataSuccess)
.error(fetchDataFailed);
function fetchDataSuccess(response) {
return response;
}
function fetchDataFailed(error) {
console.error(error);
}
}
});