I frequently find myself writing functions to handle an array of items:
- An asynchronous function run many timesin parallel, with each function using a different item of the array as its argument
- A counter that fires once all the functions have completed
Eg:
function getThings(callback){
thingsLeftToCheck = things.length;
things.forEach(function(thing){
thing.refresh(function(){
thingsLeftToCheck--;
if ( ! thingsLeftToCheck ) {
callback();
}
});
})
}
I frequently use Caolan's async library for other workflow style tasks, but I can't seem to find something that corresponds to this workflow. Eg, async.parallel is about running a number of different functions in parallel, whereas what I want is to run the same same function with different arguments:
Does async provide something like this?
Actually it looks like async.each does exactly this. A quick demo (using timeouts)
Will return: