Waiting Until All jQuery Ajax Requests are Done
Read this tutorial and learn useful information about the jQuery function that waits and then executes the function when all the ajax requests resolve.
In this tutorial, we will answer your question about how to make a function wait until all Ajax requests are done.
jQuery provides <kbd class="highlighted">when()</kbd> 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:
Javascript jQuery when function
$.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 contain the response text,
// status and jqXHR object for each of the four ajax calls.
});
function ajax1() {
// This function must return the value from calling the $.ajax() method.
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
...
});
}tip
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 <kbd class="highlighted">.when()</kbd> — jQuery Promise object, which encompasses all of the original ajax queries to have more control on your ajax scripts. You can call <kbd class="highlighted">.then()</kbd> or <kbd class="highlighted">.fail()</kbd> methods on it to add success/failure handlers.
The when() Function
The <kbd class="highlighted">.when()</kbd> 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.