Wait until all ajax jQuery calls have completed (made or rejected)

I looked through many similar questions, but the proposed solutions do not work in all cases as expected. The following code works fine when all ajax calls succeed, but if any of the ajax calls fail, then it onCompleteis called right away:

var deferredArray = $('.preload').map(function() {
    return $.get(this.href)
});
$.when.apply($, deferredArray).then(onComplete, onComplete);

Thus, there may be two cases:

  • all pending calls are successful, then onCompletecalled later - it works fine;
  • incorrect deferred call (returns HTTP 400 Bad request), then onCompletecalled immediately, without waiting for other deferred calls.

The second case presents my problem. It must always wait for all calls to complete regardless of state before calling onComplete.

jQuery 1.7.1, . , , .

+4
2

ajaxStop(). .

$( document ).ajaxStop(function() {
  // do some stuff now that all the ajax stuff has stopped
})

:

$.ajax() $.ajaxSetup(), ​​ false, .ajaxStop() .

+2

, , , bluebird.js, jquery- ajax.

:

Promise.resolve($.get("http://www.google.com")).then(function() {});

, Promise.all, ajax. , .then( .spread) .all , .

var aPass = function(){
    return Promise.resolve($.get("/echo/json/"))
};

var aFail = function(){
    return Promise.resolve($.get("/echo/jsonFake/")) // this will fail
};

var allPass = [aPass(), aPass(), aPass()];

var oneFails = [aPass(), aPass(), aFail()];


Promise.all(allPass).spread(function(a,b,c){
    console.log("All Done!");
}).catch(function(){
    console.log("NEVER FAILS!");
});;

Promise.all(oneFails).spread(function(a,b,c){
    console.log("never goes in here");
}).catch(function(){
    console.log("FAILED");
});

jsfiddle, : http://jsfiddle.net/ys598t4s/2/

+2

All Articles