如果您有以下代码:
var asyncConfig = {};
var a, b;
for(var i = 0; i < someValue; i++) {
// do something with a
// do something with b
asyncConfig[i] = function(callback) {
func(a, b, callback); // func is async
}
}
// Include some more parallel or series functions to asyncConfig
async.auto(asyncConfig);
a
和b
的值传递给func
,以便在async.auto(asyncConfig)
循环后执行for
时,上下文保留a
和b
?(每次执行a
时b
和func
的上下文不同。)
提前谢谢!
答案 0 :(得分:8)
var asyncConfig = {};
var a, b;
for(var i = 0; i < someValue; i++) {
// do something with a
// do something with b
(function(a,b){
asyncConfig[i] = function(callback) {
func(a, b, callback); // func is async
}
})(a,b);
}
// Include some more parallel or series functions to asyncConfig
async.auto(asyncConfig);
答案 1 :(得分:1)
使用bind的可能替代方案:
var asyncConfig = {};
var a, b;
for(var i = 0; i < someValue; i++) {
// do something with a
// do something with b
asyncConfig[i] = func.bind(asyncConfig, a, b);
}
// Include some more parallel or series functions to asyncConfig
async.auto(asyncConfig);
确保检查使用此支持的环境是否绑定。另外,我将“this”值绑定到asyncConfig
,这可能不适合您。
编辑:再次阅读问题,是a和b基元还是对象/数组?如果它们不是原语,那么你就想要克隆它们。