Waiting Until All jQuery Ajax Requests are Done

In this tutorial, we will answer to your question of making the function wait until all Ajax requests are done.

jQuery provides when() function which will solve this problem accepting any number of Deferred objects as arguments, and executing a function when all of them resolve.

For example, when you initiate three ajax requests and perform an action when they are done, you should act like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function (a1, a2, a3, a4) {
   // the code is executed when all requests resolve.
  // a1, a2, a3 and a4 are lists of length 3 that contains the response text,
  // status and jqXHR object for each four ajax call.
});

function ajax1() {
  // This function must return the value, from calling the $.ajax() method.
  return $.ajax({
    url: "someUrl",
    dataType: "json",
    data: yourJsonData,
    ...
  });
}
This syntax is considered to be clean, which avoids involving any global variables such as ajaxStart and ajaxStop.

It is recommended to save the object returned by .when() — jQuery Promise object, which encompasses all of the original ajax queries to have more control on your ajax scripts. You can call .then() or .fail() methods on it to add success/failure handlers.

The when() Function

The .when() function provides a way to execute callback functions based on zero or more Thenable objects, mostly on Deferred objects that represent asynchronous events. If no argument is passed to jQuery.when(), it will return a resolved Promise.