Node.js中的PostgreSQL缓慢

时间:2014-11-14 11:17:53

标签: node.js postgresql

我需要对用户进行身份验证,因此我将此函数称为:

db.authenticate = function(username,password)
{
    var query = this.query("SELECT * FROM users WHERE username = '"+username.toLowerCase()+"' AND password = crypt('"+password+"',password);");
    var found = false;
    query.on('row', function(row) {
      found = true;
      console.log("Found:",row.username);
    });       
    if(found){return true;}else{return false;}
}

问题是,该函数不会等待query.on(' row')完成并返回false ..

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

由于它是异步函数,因此您需要从回调中获取结果。

db.authenticate = function(username, password, callback) {
    var query = this.query("SELECT * FROM users WHERE username = '" + username.toLowerCase() + "' AND password = crypt('" + password + "',password);");
    query.on('row', function(row) {
        console.log("Found:", row.username);
        return callback(true);
    });
    callback(false);
}

然后你会这样称呼它:

db.authenticate(username, password, function (isAuthenticated) {
    console.log(isAuthenticated); //Will be either true or false.
}