I am writing Node.JS lambda function, where I need to invoke some API funciton with callback and pass there additional parameters.
The code looks like:
var s3 = ...;
for (var i = 0; i < data.foo.length; i++) {
    var v1 = data.foo[i].name;
    console.log("Loop: " + v1);
    var params = { ... };            
    foo.method1(params, function(err, data1) { 
         console.log("Method1: " + v1);
         s3.putObject(....);
    });
}
Here are two problems.
- I do not understand why, but inside the callback passed to - foo.method1...I have always the same value of- v1(I guess that it is the last one from the array).
- The Code checker of Amazon console advises me that it is a bad practice to create a function within a loop: 
Don't make functions within a loop.
I guess, that p.1 is somehow related to p.2 :-) That is why I've tried to create a named function and pass its reference to foo.method1. But it doesn't work as I can't pass additional parameters v1 and s3 there. I can only wrap its call like:
    foo.method1(params, function(err, data1) { 
          myCallback(err, data1, v1, s3);
    });
- what doesn't make sense, as the result is the same.
Hint: foo.method1 is apparently asynchronous.
I doubt how to solve this issue?
 
     
     
    