0

它不会变成假的!请帮助我需要将密码的值更改为 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);
});

}); 
4

2 回答 2

2

您正在处理异步和同步代码。在外部代码完成connection.query执行。只是在这一点上,是。在此之前是因为尚未执行回调。您应该在回调中执行您需要的操作:global.verifyfalseglobal.verifytrueconnection.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  
});
于 2013-10-29T17:21:17.997 回答
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);
});

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

于 2013-10-29T17:28:17.313 回答