4

my code creates two ajax call at the same time (i assume the parallelism would be more efficient). I want to load a table if both calls succeed. What's the proper way of doing this?

Progress Programmer
  • 7,076
  • 14
  • 49
  • 54
  • 2
    Batching the two requests into one and running them multi-threaded on the server-side (if that makes sense) should be more efficient, though. – Thilo Dec 21 '10 at 05:08

4 Answers4

5
var succeeded = {};

function callBackOne(){
     succeeded.one = true;
     // your other stuff
     if (succeeded.two) { bothHaveSucceeded());
}


function callBackTwo(){
     succeeded.two = true;
     // your other stuff
     if (succeeded.one) { bothHaveSucceeded());
}
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    Note that this would not work in Java with multiple threads (you would need to add synchronization to avoid race conditions), but since JavaScript does not have multiple threads (at least not in the same document), it should work reliably. – Thilo Dec 21 '10 at 05:06
1

Old question, but well, as I stumbled upon it...

I'd use the excellent async library by Caolan, particularly here you'll want to use async.parallel.

The examples written on the GitHub doc are worth a read.

https://github.com/caolan/async#parallel

Greg
  • 3,370
  • 3
  • 18
  • 20
1

I'd use a delayed task personally:

var success = {
  one: false,
  two: false
};

// Task
var task = new Ext.util.DelayedTask(function(){
   // Check for success
   if (success.one && success.two) {
      // Callback
      doCallback();
   } else {
      task.delay(500);
   }
});
task.delay(500);

// First
Ext.Ajax.request({
   ...
   success: function() {
      success.one = true;
   }
   ...
});

// Second
Ext.Ajax.request({
   ...
   success: function() {
      success.two = true;
   }
   ...
});

The task acts like a thread and will check on the status of the requests and sleep for every 500ms until they both complete.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • 3
    I wouldn't do this with timers. You'll be checking whether or not the ajax calls have finished unnecessarily and you could have time after the ajax calls finish that you're still waiting. – Miles May 14 '13 at 17:33
0

Share an integer variable that each callback checks:

// count variable
var numReturns = 0;

// same call back used for each Ajax request:
function callback() {
    numReturns++;
    if (numReturns === 2) {
        progress();
    }
}

If you need different callbacks, have each callback fire an event which does the same thing.

Miles
  • 1,615
  • 4
  • 17
  • 42