1

I have a node js function which gives me array of id's, using these id I have to call the functions from my persistent storage and each function passes the processed value to other, for this I was using water fall.

and I need to pass value from one function to other.

I am using it like this

var utilArray = utilityFunction();
var arrayofFunctions = [];
for (var index = 0; index < utilArray.length; index++) {
    var functionToInsert = null;
    if (index == 0) {
        functionToInsert = function(callback) {
            id = testArray[index] //here index is set to length of utilArray when this is proccessed 
            //function body
            callback(null, arg1);
        }
    } else {
        functionToInsert = function(arg1, callback) {
            id = testArray[index] //here also index is set to length of utilArray when this is proccessed 
            //function body
            callback(null, arg1);
        }
    }
    functionArray.push(functionToInsert);
}
async.waterfall(functionArray, function(err, result) {
    console.log("entering result function pre");
    if (err) {
        throw new Error();
    } else {
        //process result
    }

});

Here my index value becomes the length of the array and is applied like that only. If utilArray length is 3 then Index will be 3 and will be applied like that, Is there is a way I can preserve index value, like for 0 it should be 0 for 1 it should be 1 likewise.

Or is there any other way.

user3649361
  • 944
  • 4
  • 20
  • 40
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –  Sep 07 '17 at 18:42
  • 1
    Well don't use `waterfall` but `each` or `map` (or `…Series`)? – Bergi Sep 07 '17 at 19:08
  • functionToInsert = (function(index){return function(args){...}})(index) – Pavel Gatnar Sep 07 '17 at 19:10

0 Answers0