views:

167

answers:

2

I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback.

Of course, the ugly way is:

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...

Thanks in advance !

+6  A: 

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);
Sean Kinsey
And if any such pattern exist, then this is it.
Sean Kinsey
Thanks a lot Sean, it was easy, and implement something like your first solution before seeing your answer.But I like more your callback factory, it is very elegant, i will use it ;-)
Samuel Michelot
+1  A: 

Hi, 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!

Caolan