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 

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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?
I've linked some related questions. What do you mean by "passing more than 1 variable"?
i figured it out just took me a while to understand what I was lookin at.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.