thatOneGuy thatOneGuy - 4 months ago 9
Ajax Question

How to run a function once all the ajax calls have been done

Say I have this function :

function testAjax(url) {
return $.ajax({
url: url,
type: 'GET'
});
}


Now I have a number of nodes (I am using D3), I wish to loop through. Each one may or may not have some files associated. To find out if it does I get the url on the chosen node, inspect the returned data, if it has a file/files I add it to the array of files. I then wish to log the file array only after I have gone through each node and inspected it to see if it has files.

Rest of the code is similar to this :

var allFiles = [];
nodes.each(function(d) {
testAjax(d.url)
.success(function(data) {
if (data.files) {
if (data.files.length > 0) {
for (var i = 0; i < data.files.length; i++) {
allFiles.push(data.files[i])
}
}
}
})
})
//Here is where I want to log/use (call a function passing the files array as an argument) the array of files after its been completed.

Answer

Create array of promises and use $.when() to be resolved when full array is resolved

var allFiles = [];
var promises = [];

nodes.each(function(d) {
   // reference to promise
   var req=  testAjax(d.url)
        .success(function(data) {
          if (data.files) {
            if (data.files.length > 0) {
              for (var i = 0; i < data.files.length; i++) {
                allFiles.push(data.files[i])
              }
            }
          }
        })
    });
   // push to array
   promises.push(req);
});
$.when.apply(null, promises).then(function(){
    // all promises have been resolved here

}).fail(function(){
    alert('Opps ... something went wrong with one of the requests')
})
Comments