2

Im having issues with accessing the value of a variable in NodeJS. Here is some example code and the results I get.

for (var z=0, zMessageCount = Description.length; z<zMessageCount; z++){
    console.log(z);
    if(SomeOtherColumnValue[z] > 9){
        client.query('SELECT * FROM my_table WHERE some_column=' + ColumnValue[z], function (err, results) {
            if(results < 1){
                console.log(z);
            }
        })
    }
}

Here is the issue I am having. In for "for" loop the value of z is going from 0 to 14. However when I try to access it from the client.query function its value is 15. It is not adding 1 to itself for every loop. Is there something I am missing here?

4
  • 1
    z should be fine in that scope. Hmm, wild guess but what does client.query actually do with the string you pass it? I have a feeling it sends it to another non-blocking callback function and it's being executed after your loop finishes, rather than write away. What library is this? Commented Sep 19, 2011 at 4:07
  • client.query is part of node-mysql. It does appear as if it is... Is there a different way I should be doing this? Commented Sep 19, 2011 at 4:10
  • Might be wrong, but you could try var columnName = ColumnName[z]; and pass that into client.query. Defining columnName after your if statement. This might help from the z being passed as a reference into client.query Commented Sep 19, 2011 at 5:12
  • The anonymous function (the third param in client.query) creates a closure which allows it to see the value of 'z' as it continues to get incremented. +1 to generalhenry's solution below. Commented Sep 19, 2011 at 5:21

1 Answer 1

4

You need to wrap z in a function to provide scope.

for (var z=0, zMessageCount = Description.length; z<zMessageCount; z++){
    console.log(z);
    if(SomeOtherColumnValue[z] > 9){
      zQuery(z);  
    }
}

function zQuery (z) {
  client.query('SELECT * FROM my_table WHERE some_column=' + ColumnValue[z], function (err, results) {
      if(results < 1){
         console.log(z);
      }
   });
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Thank you very much. I spent hours trying to figure out where I went wrong.

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.