Async - passing variables and context preserving

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 do I pass the values ​​of the variables a and b to func , so that when async.auto(asyncConfig) is executed after the for loop, does the context of a and b remain?

(A different context a and b for each execution of func .)

Thank you in advance!

+4
source share
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); 
+7
source

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); 

Be sure to check if the environments in which you use this support are tied. Also, I bind the value of "this" to asyncConfig , this may not be right for you.

edit: Reading the question again - a or b primitives or objects / arrays? If they are not primitives, then you will want to clone them.

+1
source

All Articles