Search

How to wait until all jQuery Ajax requests are done

post-title

While working with multiple Ajax request, you might need to run specific code only after all Ajax request completed. jQuery has a when function to perform this work.

JQuery $.when

It accepts any number of arguments and runs after all argument functions are completed.

For example, you have 3 Ajax request and you want to wait for all 3 requests to complete, see the below code:

$.when(ajax1(), ajax2(), ajax3()).done(function(resp1, resp2, resp3) {
    // the code here will be executed when all four ajax requests resolve.
    console.log('All 3 ajax request complete.');
});

function ajax1() {
    return $.ajax({
        url: url1,
        dataType: "json",
        data: jsonRequestData1,
        ...
    });
}

function ajax2() {
    return $.ajax({
        url: url2,
        dataType: "json",
        data: jsonRequestData2,
        ...
    });
}

function ajax3() {
    return $.ajax({
        url: url3,
        dataType: "json",
        data: jsonRequestData3,
        ...
    });
}

Note:  resp1, resp2 and resp3 are lists of length 3 containing the response text.

Javascript Promise.all

You can use Promise.all for known ajax methods. The below Promise.all is ES standard syntax. Catch will call when any ajax request failed to complete.

Promise.all([ajax1(), ajax2()]).then(() => {
     // all requests finished successfully
     console.log('All 3 ajax request complete successfully.');
}).catch(() => {
     // all requests finished but one or more failed
})

I hope it will help you.