boom
boom

Reputation: 11666

Call variable number of functions in parallel?

Using async.parallel or custom control flow,

arr = [1, 2, 3, 4, 5, 3, 2, 3, 4, 5] //arr could be any length

get_something = function(num, cb){
  async_io(num, function (err, results){
        cb()
  });

} 

I want to run get_something() on each member of the array in "parallel". When they're all finished I'd like the callback to get called with the results.

Upvotes: 1

Views: 110

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382112

Without async :

var n = arr.length, results = new Array(n), oneIsDone = function(index, result){
   results[index] = result;
   if (--n===0) callback(results);
}
arr.forEach(function(val i){ 
    get_something(val, function(result){
       oneIsDone(i, result);
    });
});

With async :

Using async supposes your asynchronous function accepts a callback returning an error as first argument and the result as second, just like your final callback :

async.parallel(arr, get_something, callback);

If your functions don't follow this norm, you'll have to make some ugly wrappings.

Upvotes: 1

Related Questions