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 execute the next. But how?
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 execute the next. But how?
javascript is event-based, so you should never wait, rather set hooks/callbacks
You can probably just use the success/complete methods of jquery.ajax
Or you could use .ajaxComplete :
though youy should post a pseudocode of how your(s) ajax request(s) is(are) called to be more precise...
Solution given by Alex works fine. Same concept but using it a little different way (when number of calls is not known in advance)
http://garbageoverflow.blogspot.com/2014/02/wait-for-n-or-multiple-or-unknown.html
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:
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.To expand upon Alex's answer, I have an example with variable arguments and promises. I wanted to load images via ajax and display them on the page after they all loaded.
To do that, I used the following:
Updated to work for either single or multiple urls: https://jsfiddle.net/euypj5w9/
Look at my solution:
1.Insert this function (and variable) into your javascript file:
2.Buil an array with your requests, like this:
3.Create callback function:
4.Call the runFunctionQueue function with parameters:
On the basis of @BBonifield answer, I wrote a utility function so that semaphore logic is not spread in all the ajax calls.
untilAjax
is the utility function which invokes a callback function when all the ajaxCalls are completed.ajaxObjs
is a array of ajax setting objects[http://api.jquery.com/jQuery.ajax/]
.fn
is callback functionExample:
doSomething
function usesuntilAjax
.