beNerd
beNerd

Reputation: 3374

global variable scope in javascript with node.js

I have a node.js server with mysql plugin from flexiage: Here goes my code:

connection.query('SELECT * FROM students WHERE email="'+req.body.username+'" AND password="'+req.body.password+'"',function(err,rows){


    if(rows.length)
    {

        var response=new Object;
        connection.query('SELECT * FROM forums WHERE id="'+rows[0].courseInterest+'"',function(err,course){

            response.subscription=course;
            response.username=rows[0].email;
            response.password=rows[0].password;
            response.loginFailed=false;
            response.loginAccepted=true;
        });

    }
    else
    {

        var response=new Object;
        response.username="";
        response.password="";
        response.loginFailed=true;
        response.loginAccepted=false;

    }
    console.log(response);
    res.setHeader('Content-Type', 'application/json');
    res.send(response);

});

In console i just get a blank object. It does go in the if condition but unable to attach prpoerties inside the construct. My guess is the variable scope because if i do a console.log inside connection.query construct it returns the result as desired. Please shed light.

Upvotes: 1

Views: 671

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382454

No, there's no scope problem, because scopes aren't block based in JavaScript and your variable declarations are hoisted.

The response is empty because the query function is asynchronous and you log and send the response before mysql answered.

Answer the browser in the callback :

var response=new Object;
var sendResponse = function(){
    console.log(response);
    res.setHeader('Content-Type', 'application/json');
    res.send(response);
}
connection.query('SELECT * FROM students WHERE email="'+req.body.username+'" AND password="'+req.body.password+'"',function(err,rows){
    if (rows.length) {
        response=new Object();
        connection.query('SELECT * FROM forums WHERE id="'+rows[0].courseInterest+'"',function(err,course){
            response.subscription=course;
            response.username=rows[0].email;
            response.password=rows[0].password;
            response.loginFailed=false;
            response.loginAccepted=true;
            sendResponse();
        })
    } else {
        response=new Object;
        response.username="";
        response.password="";
        response.loginFailed=true;
        response.loginAccepted=false;
        sendResponse();
    }
});

Upvotes: 2

Related Questions