Michael Michael - 2 months ago 27
Node.js Question

JS Lambda scoping with async.parallel call

I am unable to capture a variable into the lambda function from its outer scope. When I run this code it executes with the same variable. I am passing the variable into the function, but I am obviously misunderstanding how scoping works with lambda.

// Add tasks to async_tasks
for(var i = 0; i < 10; i++){

var task = function(task_callback){

// I want to capture i and pass it to the function
(function(i){

exports.defaultCarWithId(connection, i, function(err, data){
if (err) {
console.log('error in query: ' + err.stack);
fCallback("[Internal Server Error]", null);
return;
}

task_callback();

});

})(i);

};

async_tasks.push(task);

}

// execute tasks
async.parallel(async_tasks, function(err, results){

fCallback(null, user);
return;

});

Answer

You can wrap the outer function:

var task = (function(i){
    return function(task_callback){
        exports.defaultCarWithId(connection, i, function(err, data){
          if (err) {
            console.log('error in query: ' + err.stack);
            fCallback("[Internal Server Error]", null);
            return;
          }

          task_callback();
        });
    };
})(i);

async_tasks.push(task);

or pass i as argument and bind it:

var task = function(i, task_callback){
    exports.defaultCarWithId(connection, i, function(err, data){
      if (err) {
        console.log('error in query: ' + err.stack);
        fCallback("[Internal Server Error]", null);
        return;
      }

      task_callback();

    });
};

async_tasks.push(task.bind(null, i));
Comments