【问题标题】:Changing the value of a global variable in a .js file更改 .js 文件中全局变量的值
【发布时间】:2013-10-29 17:15:28
【问题描述】:

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

}); 

【问题讨论】:

标签: javascript global local


【解决方案1】:

您正在处理异步和同步代码。 connection.query 在外部代码完成后执行。只有在这一点上,global.verify 才是false。在此之前 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  
});

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      相关资源
      最近更新 更多