Wait until all jQuery Ajax requests are done? Wait until all jQuery Ajax requests are done? ajax ajax

Wait until all jQuery Ajax requests are done?


jQuery now defines a when function for this purpose.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){    // the code here will be executed when all four ajax requests resolve.    // a1, a2, a3 and a4 are lists of length 3 containing the response text,    // status, and jqXHR object for each of the four ajax calls respectively.});function ajax1() {    // NOTE:  This function must return the value     //        from calling the $.ajax() method.    return $.ajax({        url: "someUrl",        dataType: "json",        data:  yourJsonData,                    ...    });}

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.


If you want to know when all ajax requests are finished in your document, no matter how many of them exists, just use $.ajaxStop event this way:

$(document).ajaxStop(function () {  // 0 === $.active});

In this case, neither you need to guess how many requests are happening in the application, that might finish in the future, nor dig into functions complex logic or find which functions are doing HTTP(S) requests.

$.ajaxStop here can also be bound to any HTML node that youthink might be modified by requst.


Update:
If you want to stick with ES syntax, then you can use Promise.all for known ajax methods:

Promise.all([ajax1(), ajax2()]).then(() => {  // all requests finished successfully}).catch(() => {  // all requests finished but one or more failed})

An interesting point here is that it works both with Promises and $.ajax requests.

Here is the jsFiddle demonstration.


Update 2:
Yet more recent version using async/await syntax:

try {  const results = await Promise.all([ajax1(), ajax2()])  // do other actions} catch(ex) { }


I found a good answer by gnarf my self which is exactly what I was looking for :)

jQuery ajaxQueue

//This handles the queues    (function($) {  var ajaxQueue = $({});  $.ajaxQueue = function(ajaxOpts) {    var oldComplete = ajaxOpts.complete;    ajaxQueue.queue(function(next) {      ajaxOpts.complete = function() {        if (oldComplete) oldComplete.apply(this, arguments);        next();      };      $.ajax(ajaxOpts);    });  };})(jQuery);

Then you can add a ajax request to the queue like this:

$.ajaxQueue({        url: 'page.php',        data: {id: 1},        type: 'POST',        success: function(data) {            $('#status').html(data);        }    });