1

I'm pretty new to Node.JS and I'm trying to build an app but I'm running into some issues which I can't seem to find a solution to. I spent quite a bit of time on Google with no luck.

Below is a little snippet which illustrate what I'm trying todo.

mysql.query('SELECT * FROM leads', function(err, res){
    for(x in res){
        id = res[x];

        mysql.query('SELECT FROM survey WHERE lead_id = ?', [id], function(x, res){
            // I want to access the id variable here but since this is in a 
            // callback the id variable could've been changed by now

            // AND THIS DOES'T ALWAYS RETURN SOMETHING OR I COULD'VE 
            // JUST USED THE LEAD_ID IN THE RETURNED DATASET
        });
    }
});

I'd like to access that id variable within the callback but due to the async nature of node the variable would've changed since the for loop finish executing before the first callback is even returned.

My question is can you pass the variable through to the the callback function? Or can someone help me with another solution.

Thanks in advance!

Ahmad

1 Answer 1

3

Instead of using a for in loop use Array.forEach, by doing this you create a closure were the id variable is captured

mysql.query('SELECT * FROM leads', function(err, res){
   res.forEach(function(x) {
        var id = x; //Captured in the closure of the mysql.query below

        mysql.query('SELECT FROM survey WHERE lead_id = ?', [id], function(x, res){
            //Do stuff with id
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.