Elvis Elvis - 4 months ago 11
Javascript Question

How to do Ajax requests with error handling and detect overall completition?

Some kinde of pseudo-synchronous question once again...

I'm looking for the best practice to run a function, after the completition of all ajax requests inside a loop.

Bad example:

var files = ["file1","file2","File3"];
var success = [];
var error = [];

for (var i = 0; i < files.length; i++) {
$.ajax({
type: "HEAD",
url: files[i]
}).done(function(){
console.log("file found");
success.push(files[i]);
doThisWhenAllFilesChecked();
}).fail(function () {
console.log("file not found");
error.push(files[i]);
doThisWhenAllFilesChecked();
})
}


Bad example 2: synchronous, just to illustrate what i'm looking for:

var files = ["file1","file2","File3"];
var success = [];
var error = [];

for (var i = 0; i < files.length; i++) {
$.ajax({
type: "HEAD",
async: false, // <-- !
url: files[i]
}).done(function(){
console.log("file found");
success.push(files[i]);
}).fail(function () {
console.log("file not found");
error.push(files[i]);
})
}
doThisWhenAllFilesChecked();

Answer

you can do this-

 var files = ["file1","file2","File3"];
    var success = [];
    var error = [];
    var k = 0;
    for (var i = 0; i < files.length; i++) {
        $.ajax({
            type: "HEAD",
            url: files[i]
            }).done(function(){
                console.log("file found");
                 k++;
                success.push(files[i]);
                doThisWhenAllFilesChecked();
            }).fail(function () {
                 k++;
                console.log("file not found");
                error.push(files[i]);
               doThisWhenAllFilesChecked();
            })
    }

    function doThisWhenAllFilesChecked(){
      if(k==files.length){
        k = 0;
        //execute code here
      }
    }