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 ?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With