7

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 and b to func so that when async.auto(asyncConfig) is executed after the for loop, the context of a and b is preserved ?

(Different context of a and b for every execution of func.)

Thank you in advance !

m_vdbeek
  • 3,704
  • 7
  • 46
  • 77
  • 2
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Felix Kling Apr 29 '13 at 12:49

2 Answers2

9
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);
neo
  • 791
  • 5
  • 7
  • Does anyone else think it's absurd that we have to do this? All I want is to pass some of my current state into this task executor. In coffeescript my code looked like this: `_metadata = do (metadata) -> (callback) -> callback(null, metadata); async.auto(metadata: _metadata)` It seems to me that some major bugs will appear in the future given this workaround. – owensmartin May 05 '14 at 05:42
  • You could also use ```myFunction.bind(null, a, b)``` ? – m_vdbeek Oct 03 '14 at 21:30
1

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.

Frances McMullin
  • 5,516
  • 2
  • 18
  • 19