How do I make a function wait until all jQuery Ajax requests are done inside another function?
In short, I need to wait for all Ajax requests to be done before I exe
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 you think 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) { }