Reputation: 10070
I have two concurrent ajax calls on the page. I want to call a function when both of them are complete (and successful).
An inefficient solution:
Unfortunately, this breaks the concurrency.
Any other way I can accomplish the same effect?
Upvotes: 2
Views: 1662
Reputation: 35091
Have a look at this answer I gave to pretty much the same question the other day, and also have a look at the demo I created to go with it (view source on that page to see the complete code). It makes much more efficient use of JavaScript's inherent capabilities and overall nature as a language than mucking about with flag variables, IMHO ;-)
Upvotes: 1
Reputation: 19593
var isASuccessful = false;
var isBSuccessful = false;
function callARequest() {
$.get("path/to/url", { params: list }, function() {
isASuccessful = true;
if (isBSuccessful) {
callMeAfterAandB();
} else {
callBRequest();
}
});
}
function callBRequest() {
$.get("path/to/other/url", { params: list }, function() {
isBSuccessful = true;
if (isASuccessful) {
callMeAfterAandB();
} else {
callARequest();
}
});
}
function callMeAfterAandB() {
// todo: something
}
Upvotes: 0
Reputation: 2146
set a global variable ajax_call_A_complete set another global varialbe ajax_call_B_complete set these two varialbes to false
No make ajax calls concurrently. In the success callback of both the ajax calls set the varialbes to true. I mean ajax call A will set ajax_call_A_complete to true and ajax call B will set varialbe ajax_call_B_complete to true.
Set a periodic time which is checking the value of these two variables every 2 seconds. When both the variables are true then fire off your dependent task.
Upvotes: -1