views:

329

answers:

3

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:

  1. make ajax call A
  2. on success for call A, make call B
  3. on success for call B, call the function

Unfortunately, this breaks the concurrency.

Any other way I can accomplish the same effect?

A: 

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.

Neeraj Singh
Assuming that it isn't possible to set those flags in any other location, a simple callback event works much better than a timer.
Jarrett Meyer
A variation could be to use a function that would be invoked at A and B completion. This function would set the global variables, depending on which call did invoke it, and then check if both variables are true. If so, then it would fire the desired function. I think it's better than have a function who gets active at every 2 seconds.
Alexandre
A: 
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
}
Jarrett Meyer
+1  A: 

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 ;-)

NickFitz