Reputation: 13771
I have a click event that fires off 3 ajax calls:
$("#button").click(function(e) {
e.preventDefault();
$.ajax(call1);
$.ajax(call2);
$.ajax(call3);
some_function() //should fire off AFTER all ajax calls are complete
});
Is there a way for me to confirm all ajax calls have been fired BEFORE firing off my some_function()
function?
Thanks in advance!
Upvotes: 5
Views: 1896
Reputation: 26331
You can use $.when
Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
$.when($.ajax(call1), $.ajax(call2), $.ajax(call3))
.done(function () {
some_function();
});
If (for some reason) you have an array of promises, then you may call this method using Function.prototype.apply():
$.when.apply($, ajaxArray)
.done(function () {
some_function();
});
Upvotes: 4
Reputation: 1159
It depends if you require success responses, but consider the following:
$.ajax({
url: "http://some.url.example.com/endpoint",
})
.always(function (data){
// Process the data
$.ajax({
url: "http://some.url.example.com/endpoint2",
})
.always(function (data2){
// Process the data
$.ajax({
url: "http://some.url.example.com/endpoint3",
})
.always(function (data) {
someFunction();
});
});
});
There is a lot more reading that could be done about jQuery deferred objects and ES6 Promises.
If you wish to set a timeout and don't care about the result, set the timeout option `$.ajax({url: "http://some.url.example.com/endpoint", timeout: 500})
OR
Set a variable in each and use window.setTimeout
to check when they've all been set, but that is horrible.
Upvotes: 0
Reputation: 4783
I suggest you to use async: false
and put the $.ajax
inside another ajax, somelike this...
$.ajax({
async: false,
// ...
complete: function() {
$.ajax({ // second ajax
async: false,
// ...
complete: function() {
$.ajax({ // second ajax
async: false,
// ...
complete: function() {
some_function();
}
});
}
});
}
});
Upvotes: 2