将额外参数传递给异步映射 [英] Pass extra argument to async map

查看:75
本文介绍了将额外参数传递给异步映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async.map的签名是map(arr,iterator,callback)( https:// github。 com / caolan / async #map

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

我有一个 var context // object
我需要将它传递给迭代器。我该怎么做?

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

推荐答案

你可以用两种方式使用bind:

You can use bind, in two ways:

iterator.bind(context)

这将使迭代器函数中的 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)

这将使 context 可用作迭代器函数的第一个参数。因此,而不是迭代器签名是 iterator(item,callback),它变成 iterator(context,item,callback)

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).

简单演示:

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

这篇关于将额外参数传递给异步映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆