Skip to content Skip to sidebar Skip to footer

How To Get The Two Parameters Of Two Asynchronous Functions?

var o = new X(); o.setFooCallback1(function(result1){ }); o.setFooCallback2(function(result2){ }); o.foo('xxx'); as you can see, when I call o.foo(), there're two callbacks will

Solution 1:

You need to implement what is known as the semaphore pattern

Here is a hands-on implementation:

var o = newX()
  , n = 0
  , result1, result2

functioncheckResults(){
    if (--n > 0) return;
    var y = newY(result1, result2)
}

o.setFooCallback1(function(res){
    result1 = res
    checkResults()
})

o.setFooCallback2(function(res){
    result2 = res
    checkResults()
})

Or an object-oriented approach:

functionSemaphore(callback){
    this.callback = callback
    this.count = 0this.args = []
}
Semaphore.prototype.check = function(){
    if (--this.count <= 0)
        this.callback.apply(null, this.args)
}
Semaphore.prototype.queue = function(){
    var self = this
    self.count++
    returnfunction(res){
        self.args.push(res)
        self.check()
    }
}

var fooResults = newSemaphore(function(res1, res2){
    var y = newY(res1, res2)
})

o.setFooCallback1(fooResults.queue())
o.setFooCallback2(fooResults.queue())

Note that it only captures the first callback arguments, but you can easily extend this to whatever you need.

Solution 2:

Basically you need to add another layer, that fires a callback after both callbacks from the first layer have executed, probably in a different object. The answer here is pretty good:

jQuery callback for multiple ajax calls

Solution 3:

Call the same function from, inside both callbacks, but only actually do anything once they have both returned, like this:

(function(){
  var y, r1, r2;

  functionrunWhenBothReturn() {
    if(r1 && r2) { //check both are set to a non-falsy value
      y = newY(r1, r2); 
    }
  }

  var o = newX();

  o.setFooCallback1(function(result1){
    r1 = result1;
    runWhenBothReturn();
  });

  o.setFooCallback2(function(result2){
    r2 = result21;
    runWhenBothReturn();
  });

  o.foo("xxx"); 

})();

Notice that i have added a closure so that y, r1 and r2 doesn't become global variables, but stay local to the task.

If either r1 or r2 can have values that evaluate to false, then make sure to update the if sentence accordingly :)

Post a Comment for "How To Get The Two Parameters Of Two Asynchronous Functions?"