Does node-async handle the common 'fetch in parallel' workflow?

165 Views Asked by At

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?

1

There are 1 best solutions below

0
On

Actually it looks like async.each does exactly this. A quick demo (using timeouts)

var items = ['one','two']
var results = []
var doStuff = function(item, callback){
  setTimeout(function(){
    results.push('result'+item)
    callback(null)
  })
}

Will return:

[ 'resultone', 'resulttwo' ]