更改.js文件中全局变量的值

时间:2013-10-29 17:15:29

标签: javascript global local

它不变为假!!请帮忙 我需要将Password的值更改为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);
});

}); 

2 个答案:

答案 0 :(得分:2)

您正在处理异步和同步代码。在外部代码完成后,connection.query执行。仅在此时,global.verifyfalse。在此之前global.verifytrue,因为connection.query的回调尚未执行。你应该在回调中做你需要的事情:

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  
});

答案 1 :(得分:0)

代码看起来很奇怪,没有上下文这是一个很难回答的问题,但通常异步行为是一件好事,但如果出于某种奇怪的原因你真的需要它同步,你总是可以伪造它:

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);
});

注意:这通常不是一个好主意,但作为最后的手段!