pixelfreak
pixelfreak

Reputation: 17834

Async.js eachSeries without stopping on error

I have an array I need to process asynchronously in order. If one of them failed, I need to continue processing the rest but I need to keep track of that error so I can do something at the end of the the entire process.

Reading the documentation, it looks like this feature isn't really built into eachSeries. It seems like I'd have to call callback() on every task, indicating that it's always successful and keep track of the errors on the side myself. Is this correct?

Upvotes: 0

Views: 1809

Answers (2)

Leo
Leo

Reputation: 3872

In the meantime, reflect and reflectAll have been added to async, to cover this scenario.

Example (from official docs):

async.parallel([
    async.reflect(function(callback) {
        // do some stuff ...
        callback(null, 'one');
    }),
    async.reflect(function(callback) {
        // do some more stuff but error ...
        callback('bad stuff happened');
    }),
    async.reflect(function(callback) {
        // do some more stuff ...
        callback(null, 'two');
    })
],
// optional callback
function(err, results) {
    // values
    // results[0].value = 'one'
    // results[1].error = 'bad stuff happened'
    // results[2].value = 'two'
});

Docs:

Async Reflect

Upvotes: 2

Leah Zorychta
Leah Zorychta

Reputation: 13419

keeping track of the error yourself here isn't necessarily a bad thing:

var errors = [];
async.eachSeries([1,2,3], function(data, cb) {
  if(some_error_case) {
    errors.push(data);
  }
  cb(null);
}, function(data) {
  console.log('errors happened: ', errors);
});

always call cb(null) even when there's an error, otherwise it will stop the loop prematurely. Then push any errors into the errors array and deal with them in the callback at the end.

Upvotes: 5

Related Questions