Lucas Randisi Lucas Randisi - 2 months ago 22
jQuery Question

Execute a function after multiples ajax requests

Im trying to execute a function after 6 ajax calls (indluding the ".done" part after each one)

function showReports(array_monitor){
$.ajax({
method: "GET",
url: array_monitor[0],
datatype: "text",
}).done(function(xml) {
monitorName = array_monitor[1];

convert(xml, monitorName);
});
};


I have tried with $.when but it seems that is not working as I wanted

Edit:



I've included a global counter and the function after all the calls have to compress some files that are created, is it neccesary to set a timeout to wait or is $.when enough?

function zipAll(){
$.ajax({
method: "POST",
url: "zipAll.php",
}).done(function(){
window.location = "uptimeReports.zip";
console.log("hola");
});
}

Answer

$.ajax returns a promise-like object. You feed that (all 6 of those) to $.when. Also, don't use .done but .then for the sake of consistency since promises use .then

function showReports(array_monitor){
  return $.ajax(...).then(function(xml){
    // Do some parsing
    return finalValue;
  });
}

$.when.apply(null, [
  showReports(...),
  showReports(...),
  showReports(...),
  showReports(...),
  showReports(...),
  showReports(...),
]).then(function(result1, result2,...){
  // All done
});

Also ensure that you return a value from showReports's .then callback. It's the resolved value for the promise, that becomes the value passed into $.when.

Comments