mimzah
mimzah

Reputation: 31

Changing the value of a global variable in a .js file

it doesnt change to false!! please help i need to change the value of Password to false

//password check
{

 connection.connect(function(){
    connection.query('select * from rencho2.user',function(err,results){ 
        if(results[0].passwd==p){
            console.log("correct");
        else { 
               global.verify="false";
           console.log("Incorrect. "); //here its false                             
        }                                 
         //here its false
   }); 
                //here it becomes true -- why??

    send = { 
        "UserName": body.UserName,
        "Password": global.verify
    }
    body1=JSON.stringify(send);
});

}); 

Upvotes: 0

Views: 87

Answers (2)

adeneo
adeneo

Reputation: 318342

The code seems strange, and with no context it's a hard question to answer, but generally asynchronous behaviour is a good thing, but if for some strange reason you really need it to be synchronous you can always fake it :

connection.connect(function(){
    var done = false;

    connection.query('select * from rencho2.user', function(err,results) { 
        if(results[0].passwd == p){
            console.log("correct");
        } else { 
            global.verify = false;
            console.log("Incorrect. ");
        }
        done = true;
    }); 

    while (done == false) {};

    send = { 
        "UserName": body.UserName,
        "Password": global.verify
    }
    body1 = JSON.stringify(send);
});

note: this is generally not a good idea, but will work as a last resort !

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95588

You're dealing with asynchronous and synchronous code. connection.query executes after the outer code is done. It is only at that point, global.verify is false. Prior to that global.verify is true because the callback to connection.query has not executed yet. You should do what you need from within the callback:

connection.query('select * from rencho2.user',function(err,results){ 
    if(results[0].passwd==p) {
        console.log("correct");
    } else { 
        global.verify="false";
        console.log("Incorrect. "); //here its false                             
    }                                 

    send = { 
        "UserName": body.UserName,
        "Password": global.verify
    };

    body1 = JSON.stringify(send);

    //do what you need with body1  
});

Upvotes: 2

Related Questions