Javascript: connection.query function is breaking my for loop

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 

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);