質問

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);
});

他のヒント

With arrow functions you can curry your functions and pass in extra parameters:

async.map([1,2,3], context => (item, callback) => {
  // you now have access to context, item, and callback here
}, (err, results)=>{
  // async.map callback function
});

I like to put my functions outside the async functions to keep things clean:

const processItem = context => (item, callback) => {
  // process items here
};

async.map([1,2,3], processItem(context)(item, callback), (err, results)=>{
  // async.map callback function
});

With arrow functions the best practice is to use async.apply. async.apply provide the ability for adding extra parameters, which will be passed to the target function as first parameters. Here is an example code:

processItemFuction(context, item, callback) {
    //Here you can access context as well
}

async.map([1,2,3]), async.apply(processItemFuction, context), (err, res) {
    // async.map callback function
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top