【发布时间】:2014-01-19 21:32:37
【问题描述】:
async.map 的签名是 map(arr, iterator, callback) (https://github.com/caolan/async#map)
我有一个var context //object
我需要将它传递给迭代器。我该怎么做?
【问题讨论】:
标签: javascript node.js async.js
async.map 的签名是 map(arr, iterator, callback) (https://github.com/caolan/async#map)
我有一个var context //object
我需要将它传递给迭代器。我该怎么做?
【问题讨论】:
标签: javascript node.js async.js
您可以通过两种方式使用绑定:
iterator.bind(context)
这将使context 在迭代器函数中作为this 可用。
另一种方法是创建偏函数:
iterator.bind(null, context)
这将使context 可用作迭代器函数的第一个参数。所以迭代器签名不是iterator(item, callback),而是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);
});
【讨论】:
item 在被async.map() 调用时仍将传递给iterator。 .bind() 只是将context 设置为item 之前的额外参数。
使用箭头函数,您可以对函数进行 curry 并传入额外的参数:
async.map([1,2,3], context => (item, callback) => {
// you now have access to context, item, and callback here
}, (err, results)=>{
// async.map callback function
});
我喜欢将我的函数放在异步函数之外以保持整洁:
const processItem = context => (item, callback) => {
// process items here
};
async.map([1,2,3], processItem(context)(item, callback), (err, results)=>{
// async.map callback function
});
【讨论】:
对于箭头函数,最佳做法是使用 async.apply。 async.apply 提供添加额外参数的能力,这些参数将作为第一个参数传递给目标函数。这是一个示例代码:
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
}
【讨论】: