Skip to content

Instantly share code, notes, and snippets.

@moechofe
Last active August 29, 2015 14:19
Show Gist options
  • Save moechofe/213b7e5fd557343ae51c to your computer and use it in GitHub Desktop.
Save moechofe/213b7e5fd557343ae51c to your computer and use it in GitHub Desktop.

waitgroup

Simple helper to run asynchronous functions and wait for them to finish before calling a callback function.

Callback use the node.js format:

  cb = function(err, result...){...}

Example with dummy asynchronous functions:

waitgroup([function(cb){

    setTimeout(function(){
        cb(null,2);
    }, 2);

}, function(cb){

    setTimeout(function(){
        cb(null,1);
    }, 1);

}], function(err, results){
    console.log("Done",results);
});

waitgroup

void = waitgroup( array funcs, function done )

Wait for all functions sent in the funcs array to complete a call the done function.

  • array funcs:

    An array of asynchronous function. See below.

  • function done:

    Will be called when all funcs functions are done. Or when a funcs function produce an error.

funcs

function(func done)

The callback passed as argument to every funcs function when they are call by workgroup().

  • func done:

    The callback to indiquate when a funcs function is finished, or produce an error.

done

function(? err, ? result)

TODO: finish it

var waitgroup = function(funcs, cb)
{
var done = funcs.length;
var results = [];
var error = null;
for(var i=0,l=funcs.length; i<l; i++)
{
funcs[i](function(index){return function(err,result){
if(err || error) return error || ((error = err) && cb && cb(err));
results[index] = result;
if(--done == 0 && cb) cb(null,results);
};}(i));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment