0

I commented the values on the first (and only) execution of my for loop. It doesn't seem to matter what I do... after connection.query my for loop is always given a value that escapes the loop. No idea why. I can provide more examples. Anyone know what might be going on and how I can get around the problem? Here is a snippet of code that has this problem. The mysql plugin for node.js i'm using is here

https://github.com/felixge/node-mysql

for (j=0;j<rows[i].movelimit;j++){
            //j=0
               sql2="SELECT x, y, land FROM map WHERE collision = 0 AND x>"+(lastX-55)+" AND x<"+(lastX+55)+" AND y>"+(lastY-55)+" AND y<"+(lastY+55)+" AND land='"+rows[i].land+"'"+restrictions;
               connection.query(sql2, function(err, move, fields) {
            //j=rows[i]movelimit 
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Shawn
  • 871
  • 2
  • 12
  • 22

1 Answers1

3

It seems to be an asynchronous callback. Therefore, your loop variable j which is out of the scope of the callback function, will always evaluate to the last value it got assigned before the loop ended. See also javascript for loop unexpected behaviour or JavaScript closure inside loops – simple practical example.

Use a closure:

function getCallbackFn(index) {
    return function(err, move, fields) {
        ....
        // "index" will always point to the function argument
    };
}
for (j=0;j<rows[i].movelimit;j++) {
    var sql2 = ...
    connection.query(sql2, getCallbackFn(j));
}

Shorter, inline IEFE:

for (j=0;j<rows[i].movelimit;j++) (function(j){
    var sql2 = ...
    connection.query(sql2, function(err, move, fields) {
        ....
        // "j" points to the function argument
    });
})(j);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I've never seen this technique before I'll try it but not 100% sure whats going on I understand I can't pass variables into the function Could you show how to pass more than 1 variable? – Shawn Jul 28 '12 at 14:50
  • I've linked some related questions. What do you mean by "*passing more than 1 variable*"? – Bergi Jul 28 '12 at 14:57
  • i figured it out just took me a while to understand what I was lookin at. – Shawn Jul 28 '12 at 23:41