If you have the following code :
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);
- How can you pass the values of the variables
a
andb
tofunc
so that whenasync.auto(asyncConfig)
is executed after thefor
loop, the context ofa
andb
is preserved ?
(Different context of a
and b
for every execution of func
.)
Thank you in advance !
If you have the following code :
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);
- How can you pass the values of the variables
a
andb
tofunc
so that whenasync.auto(asyncConfig)
is executed after thefor
loop, the context ofa
andb
is preserved ?
(Different context of a
and b
for every execution of func
.)
Thank you in advance !
Share Improve this question asked Apr 29, 2013 at 12:48 m_vdbeekm_vdbeek 3,7848 gold badges49 silver badges79 bronze badges 1- 2 possible duplicate of Javascript closure inside loops - simple practical example – Felix Kling Commented Apr 29, 2013 at 12:49
2 Answers
Reset to default 9var 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);
possible alternative using 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);
Make sure to check if the environments where you use this support bind. Also, I am binding the "this" value to asyncConfig
, this may not be appropriate for you.
edit : Reading over the question again, are a and b primitives or objects/arrays? If they aren't primitives, then you'll want to clone them.