Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass extra argument to async map

Signature for async.map is map(arr, iterator, callback) (https://github.com/caolan/async#map)

I have a var context //object and I need to pass this to the iterator. How do i do this ?

like image 593
user644745 Avatar asked Jan 02 '14 12:01

user644745


1 Answers

You can use bind, in two ways:

iterator.bind(context)

This will make context available within the iterator function as this.

The other method is to create a partial function:

iterator.bind(null, context)

This will make context available as the first argument to the iterator function. So instead of the iterator signature being iterator(item, callback), it becomes iterator(context, item, callback).

Simple demo:

// first:
async.map([1, 2, 3], function(item, callback) {
  callback(null, item * this.mult);
}.bind({ mult: 5 }), function(err, results) {
  console.log('R', results);
});

// second:
async.map([1, 2, 3], function(ctx, item, callback) {
  callback(null, item * ctx.mult);
}.bind(null, { mult: 5 }), function(err, results) {
  console.log('R', results);
});
like image 153
robertklep Avatar answered Oct 01 '22 07:10

robertklep