-4

I can't access data[i] in the callback function.
This is my code:

var data = ['HI', 'Hi2'];

for(var i=0;i<data.length;i++){
console.log(data[i]); // Just works fine
//use mysql to query database
mysql.query('some sql stuff', function(err,result){
  console.log(data); // Just works fine
  console.log(data[i]); // Doesn't work
  }
);
} 
  • 2
    I think the `i` doesn't exist inside your `mysql.query` return. Try `console.log(i)` instead of `console.log(data[i])` – driconmax Nov 22 '16 at 20:04
  • thats not what i'm looking for. i want the number i of the data array – vincent0110 Nov 22 '16 at 20:08
  • Though probably not relevant to your issue - which I cannot see an obvious solution to - you're likely missing a `var` in front of your iteration variable declaration (i.e., `var i = 0`). – Nick Broderick Nov 22 '16 at 20:11
  • I said Try `console.log(i)` to check if `i` is working in that part of the code.......... – driconmax Nov 22 '16 at 20:13
  • sry i copied the code very bad. in my code i've tried out with and without `var i=0` – vincent0110 Nov 22 '16 at 20:14
  • im sorry. `i` is not correct. i have 2 elements and `i = 2` (0,1,2) it should be 0 + 1, not 2 + 2 – vincent0110 Nov 22 '16 at 20:15
  • What does the second console.log output? Do you get Hi2 twice? – Ryan Nov 22 '16 at 20:17
  • I dont think `i` is a global variable. – andershagbard Nov 22 '16 at 20:18
  • function(err,result){ console.log(data); // Just works fine console.log(data[i]); // Doesn't work } this is a callback function that won't be called until the mysql data is returned. This does not stop your loop, and i will be whatever value it is assigned as in the loop when that function does get called. Do a search for closures inside a loop. – Chris Caviness Nov 22 '16 at 20:20
  • yes ryan. the result is twice hi2 – vincent0110 Nov 22 '16 at 20:20
  • http://stackoverflow.com/questions/6978911/closure-inside-a-for-loop-callback-with-loop-variable-as-parameter – Chris Caviness Nov 22 '16 at 20:23

1 Answers1

0

By the time your first SQL query finishes the loop is complete and the value of i is 1 so I would expect your code to log hi2 twice. Move your query outside of the for loop.

var data = ['HI', 'Hi2'];

for(i=0;i<data.length;i++){
  console.log(data[i]); // Just works fine
  //use mysql to query database
  logStuff(i);
} 

function logStuff(i) {
  mysql.query('some sql stuff', function(err,result){
    console.log(data); // Just works fine
    console.log(data[i]); // Doesn't work
  });
}
Ryan
  • 5,845
  • 32
  • 27
  • `data.forEach(function(value, index){ mysql.query('...', function(err, result){ console.log(index, value, err || result); }); })` – Thomas Nov 22 '16 at 20:46