0

How would i pass an indexer from an outer for loop into a callback function within that for loop. My function within is the client.get() (see my code for desired output).

some_array = ['a', 'b', 'c'];

for(var i = 0; i < some_array.length; i++){
    console.log(some_array[i]); // This prints a, b, c as expected
      client.get("http://foo/" + some_array[i] + "/bar", function (data, response) {
          console.log(some_array[i]); // THE PROBLEM: This prints undefind, I need it to print the exact same as the first console.log() statement
          console.log(i); // This also prints undefined
          console.log(some_array); // This prints ['a', 'b', 'c']
    }
}

Since some_array is global i can print it just fine within the callback, however, i can not access any of the elements within some_array, how do i do this?

BLang
  • 930
  • 3
  • 16
  • 35

1 Answers1

3

Easiest way is to use let instead of var for you incrementer..

for(let i = 0; i < some_array.length; i++){
  /// code here...
}

Since let is block scope it is the same anywhere in the block, even in an async function's callback.

Here's an example looping with an async function to demonstrate the differences.

var a = [1,2,3,4];

for(let i=0; i<a.length; i++){
  setTimeout(function(){
     console.log("Using let", a[i]);
  }, 50);
}

for(var i=0; i<a.length; i++){
  setTimeout(function(){
     console.log("Using var", a[i]);
  }, 50);
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116