That depends on what you want it to do.  This seems to execute each item
serially.  You can do them all parallel and abort on the first error like
this:

function asyncForEach(array, worker, callback) {
  var len = array.length;
  var results = new Array(l);
  if (!len) return callback(null, results);
  var left = len;
  for (var i = 0; i < len; i++) {
    start(i);
  }
  function start(i) {
    worker(array[i], i, array, function (err, result) {
      if (err) return callback(err);
      results[i] = result;
      if (!--left) callback(null, results);
    });
  }
}


On Wed, Apr 11, 2012 at 2:07 PM, Tim Price <price.ti...@gmail.com> wrote:

> How would one better write this function?
>
> Array.prototype.forLoop = function(worker, callBack) {
> var self = this;
> var returnData = [];
> var loop = function(i) {
> if(i === self.length) {
> return callBack(returnData);
> }
> process.nextTick(function() {
>
> worker.call(self, self[i], function(d) {
>
> returnData.push(d);
> loop(++i);
> });
> });
> }
> loop(0);
> };
>
>
> and you would use it like so
>
>
> ['sdf', 'sdfsdf'].forLoop(function(item, done) {
> console.log(item, done)
> done(item)
> }, function(result) {
> console.log(result)
> })
>
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nodejs@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nodejs@googlegroups.com
To unsubscribe from this group, send email to
nodejs+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to