Async: using .reflect with .each

Created on 14 Apr 2016  路  2Comments  路  Source: caolan/async

Hi, not sure if my syntax is wrong or if this is a bug, but:

  var arr = ['one', 'two', 'three'];

  async.each(arr, async.reflect(function(val, done){
    if(val === 'two'){
      done(val);
    } else {
      done(null, val);
    }
  }), function(err, results){
    // I would expect
    // err = null
    // results[0].value = 'one'
    // results[1].error = 'two'
    // results[2].value = 'three'

    // Instead I see
    // err = null
    // results = undefined
  });

version: "async": "~2.0.0-rc.3"

question

Most helpful comment

Hey @JCarran0 ,

This is expected behaviour each, as it doesn't consider the result of each iteration. The final callback has a signature of just (err).

If you need the results, use map. It's the exact same code, just replace async.each with async.map

var arr = ['one', 'two', 'three'];

async.map(arr, async.reflect(function(val, done) {
    if(val === 'two'){
        done(val);
    } else {
        done(null, val);
    }
}), function(err, results) {
    // err is still undefined
    // results is now:
    // [ { value: 'one' }, { error: 'two' }, { value: 'three' } ]
});

All 2 comments

Hey @JCarran0 ,

This is expected behaviour each, as it doesn't consider the result of each iteration. The final callback has a signature of just (err).

If you need the results, use map. It's the exact same code, just replace async.each with async.map

var arr = ['one', 'two', 'three'];

async.map(arr, async.reflect(function(val, done) {
    if(val === 'two'){
        done(val);
    } else {
        done(null, val);
    }
}), function(err, results) {
    // err is still undefined
    // results is now:
    // [ { value: 'one' }, { error: 'two' }, { value: 'three' } ]
});

Of course! Makes sense, thanks.

Was this page helpful?
0 / 5 - 0 ratings