JavaScript的:执行一堆异步方法的一个回调 [英] javascript: execute a bunch of asynchronous method with one callback
问题描述
我需要执行一帮异步方法(客户端SQLite数据库),并呼吁只有最后一个回调。
I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback.
当然,丑陋的方式是:
execAll : function(callBack) {
asynch1(function() {
asynch2(function() {
...
asynchN(function() {
callBack();
})
})
});
}
但我知道有更好的方法来做到这一点。直觉上我会发现,当所有回拨一直被称为一个计数器来调用回调最终
But I know there are better ways to do it. Intuitively I would detect when all call back has been called with a counter to call the final callback.
我觉得这是一种常见的设计模式,所以如果有人可以点我在正确的方向...
I think this is a common design-pattern, so if someone could point me in the right direction...
在此先感谢!
推荐答案
这是很容易
var callback = (function(){
var finishedCalls = 0;
return function(){
if (++finishedCalls == 4){
//execute your action here
}
};
})();
就在这个回调传递给所有的方法,一旦它被称为4次就会执行。
Just pass this callback to all your methods, and once it has been called 4 times it will execute.
如果你想使用工厂这点,你可以做以下
If you want to use factory for this then you can do the following
function createCallback(limit, fn){
var finishedCalls = 0;
return function(){
if (++finishedCalls == limit){
fn();
}
};
}
var callback = createCallback(4, function(){
alert("woot!");
});
async1(callback);
async2(callback);
async3(callback);
async4(callback);
这篇关于JavaScript的:执行一堆异步方法的一个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!