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