Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async - passing variables and preserving context

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 !

like image 570
m_vdbeek Avatar asked Apr 29 '13 12:04

m_vdbeek


2 Answers

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);
like image 136
neo Avatar answered Nov 07 '22 19:11

neo


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.

like image 20
Frances McMullin Avatar answered Nov 07 '22 18:11

Frances McMullin