如何获得的两个异步函数的两个参数? [英] 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");
你可以看到,当我打电话 o.foo()
,这里有两种回调将两个结果被解雇, RESULT1
和 RESULT2
,我想要做的是使用通 RESULT1
和 RESULT2
我的构造函数来创建一个对象:
as you can see, when I call o.foo()
, there're two callbacks will be fired with two results, result1
and result2
, what I want to do is use pass result1
and result2
to my constructor function to create an object:
var y = new Y(result1, result2);
但RESULT1和RESULT2有不同的时间(异步),我怎么能处理呢?结果
PS:类 X
是从别人的库,我不能修改它的FPGA实现
But result1 and result2 come in different time(asynchronous), how could I handle this?
ps: the class X
is from others' library, I can't modify it's implemention
推荐答案
您需要实现所谓的的信号灯模式
下面是一个动手实现:
var o = new X()
, n = 0
, result1, result2
function checkResults(){
if (--n > 0) return;
var y = new Y(result1, result2)
}
o.setFooCallback1(function(res){
result1 = res
checkResults()
})
o.setFooCallback2(function(res){
result2 = res
checkResults()
})
或面向对象的方法:
function Semaphore(callback){
this.callback = callback
this.count = 0
this.args = []
}
Semaphore.prototype.check = function(){
if (--this.count <= 0)
this.callback.apply(null, this.args)
}
Semaphore.prototype.queue = function(){
var self = this
self.count++
return function(res){
self.args.push(res)
self.check()
}
}
var fooResults = new Semaphore(function(res1, res2){
var y = new Y(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.
这篇关于如何获得的两个异步函数的两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!