0

我正在使用带有 postgreSQL 的 nodeJs express 3 框架,我正在使用下面的脚本在 DB 中查找用户名并填充一个变量,以便我可以将其传递给我的视图。这是我的脚本:

app.js
var app = express();
app.use(express.bodyParser());
......
function fncCheckUsernameAvailability(vstrUsername){
    var pg = require("pg");
    var client = new pg.Client({user: 'xxx', password: 'xxxx', database: 'xxx', host: 'example.com'});
    var response = "";
    client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
 client.query("SELECT username FROM users WHERE username ='"+vstrUsername+"'", function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
        if(result.rows[0] == undefined){
            //console.log("Username available");
            response = "Username available";//Populating The variable here
        }else{
            //console.log("Username already taken");
            response = "Username already taken";//Populating The variable here
        }
    client.end();
  });
    });
    return response;
}


app.post("/Signup", function(req, res){
var username = req.body.username;
var Response = fncCheckUsernameAvailability(username);
console.log(Response);
}

响应变量总是“未定义”,那么我怎样才能让该脚本等到数据库检查完成以填充“响应”变量?

4

1 回答 1

3

您不能将返回值放入异步函数中。相反,您需要使用回调,这就是您的代码的样子:

function fncCheckUsernameAvailability(vstrUsername, callback) {
  client.connect(function(err) {
    if (err) {
      callback(err, null);
      return;
    }

    client.query("SELECT username FROM users WHERE username ='" + vstrUsername + "'", function (err, result) {
      client.end();
      if (err) {
        callback(err, null);
        return;
      }

      if (result.rows[0] == undefined) callback(null, 'Username available.');
      else callback(null, 'Username taken.');
    });
  });
};

你会使用这样的函数:

app.post("/Signup", function(req, res) {
  var username = req.body.username;
  fncCheckUsernameAvailability(username, function(err, result) {
    console.log(result);
  });
});
于 2013-09-13T19:31:37.880 回答