laggingreflex
laggingreflex

Reputation: 34647

Async.map - make it ignore the error(s), and process the entire list

I have to process an array with async

var arr = [1,2,3,4];
Async.map(arr, iterator, callback);

The iterator function, which I have no control over, would throw errors for all values but, say 4.

function iterator(val, cb) {
    console.debug('processing', val);
    if (val == 4) cb();
    else cb(new Error(val));
}

What async would do is

If iterator passes an error to his callback, the main callback (for the map function) is immediately called with the error.

So I get

processing 1
[Error: 1]
processing 2
processing 3
processing 4

What I want is that it shouldn't immediately call the callback with an error, but wait til it processes the entire list, which it does anyways, and only then call the callback.

Is this possible? Or is there an alternative to Async.map that behaves in this way?

Upvotes: 1

Views: 2877

Answers (2)

Alvaro Gómez
Alvaro Gómez

Reputation: 39

I had a similar problem where my iterator would send me nulls to my array, so I used async.mapLimit function.

mapLimit(coll, limit, iteratee, callback)

See:

https://caolan.github.io/async/docs.html

I hope this helps.

Upvotes: 0

Brendan
Brendan

Reputation: 3493

If iterator passes an error to his callback, the main callback (for the map function) is immediately called with the error

https://github.com/caolan/async#map

You could instead pass back a null value to the callback instead of erroring out.

function iterator(cb, trans) {
  try {
    // something
    cb(null, transformed);
  }
  catch (ex) {
    // log the error perhaps
    cb(null, null);
  }
}

Since you don't have control over the iterator you could write a wrapper around it.

Assume their iterator is called their_iterator.

function my_iterator(cb, trans) {
  var my_cb = function(their_err, their_trans) {
    if (their_err) {
      // log error
        cb(null, null);
    }
    else {
        cb(null, their_trans);
    }
  }

  their_iterator(my_cb, trans);
}

Async.map(arr, my_iterator, callback);

Upvotes: 2

Related Questions