1

Currently I am trying to run in parallel the same function with different arguments using Node.JS

For this I use Async.js and i am struggling trying to push/stack functions to an array. The problem is that the functions are executed with the same arguments. This is what I have:

var async = require("async");
var array = [];
var x = [1,2,3,4];

// This portion of code works perfect and the arguments are passed perfectly
// The results that i am getting are: [100, 200, 300, 400]
array.push(function(callback){ callback(null,calculate(x[0]))});
array.push(function(callback){ callback(null,calculate(x[1]))});
array.push(function(callback){ callback(null,calculate(x[2]))});
array.push(function(callback){ callback(null,calculate(x[3]))});

// This portion of code does not work and I dont know why ... 
// The results that i am getting are: [400, 400, 400, 400]
// Obviusly the function is receiving the same argument a=4 everytime is called
for (i=0;i<3;i++){
    array.push(function(callback){ callback(null,calculate(x[i]))});
}

async.parallel(array,function(err,result){
    if (err) {
        console.log(err);
    return;
    }
    console.log("Results are: " + result);
});


function calculate(a) {
  return a*100
}

Any idea of what is wrong? Thanks

2 Answers 2

1

try this, it is an issue of closure

for (i=0;i<3;i++){
   (function(i){
    array.push(function(callback){ callback(null,calculate(x[i]))});
   })(i)
}
1

let is what you need.

'use strict';
for (let i=0;i<3;i++){
    array.push(function(callback){ callback(null,calculate(x[i]))});
}
1
  • absolutely, i didn't use let as didn't know if he/she was using a transpiler - but yes, "let" is a good avenue too! Commented Apr 8, 2016 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.