javascript: execute a bunch of asynchronous method with one callback
Solution 1:
this is easy
var callback = (function(){
var finishedCalls = 0;
return function(){
if (++finishedCalls == 4){
//execute your action here
}
};
})();
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);
Solution 2:
I've written some async utilities you might find useful, allowing you to write your example as:
function(callback) {
async.series([
asynch1(),
asynch2(),
...
asynchN()
], callback);
}
Or, if you wanted to run them in parallel, as:
function(callback) {
async.parallel([
asynch1(),
asynch2(),
...
asynchN()
], callback);
}
There are loads of other useful functions like async map/reduce too:
http://caolanmcmahon.com/async.html
Hope that helps!
Solution 3:
You should consider using Deferred pattern for asynchronous methods. You can get more information from the this StackOverflow question and answers:
What are the differences between Deferred, Promise and Future in JavaScript?
The marked answer from jnewman was good actually!
Hope this helps.