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屋!