我在 nodeJS 中有一个脚本连接到我的 postgres 数据库,问题是在回调方法上我正在启动一个变量,但它似乎总是空的,这是我的 app.js 脚本:
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
function fncCheckUsernameAvailability(vstrUsername, callback) {
var pg = require("pg");
var client = new pg.Client({user: 'xxx', password: 'xxx', database: 'xxx', host: 'xxx.com'});
client.connect(function(err) {
if (err) {
callback(err, null);
return;
}
client.query("SELECT username FROM users WHERE username ='"+vstrUsername+"'", function(err, result) {
if (err) {
callback(err, null);
return;
}
if (result.rows[0] == undefined) {
callback(null, null);
}else {
callback(null, 'Username already taken');
}
client.end();
});
});
}
app.post("/Signup", function(req, res){
var username = req.body.username;
var usernameError = '';
var errors = [];
if (!ck_username.test(username)) {
errors[errors.length] = "Invalid username";
usernameError = "Invalid username";
}
if (ck_username.test(username)) {
//The issue starts here
fncCheckUsernameAvailability(username, function(err, result) {
if(result != null){
errors[errors.length] = result;
usernameError = result; // usernameError is always empty
console.log(result);//This is printed in console, I can see the result
}
});
}
if (errors.length > 0) {
res.render('Signup.ejs', {
layout:false,
usernameError:usernameError // usernameError is sent to the view empty
});
}
else{
res.render('Signup.ejs', {
layout:false,
usernameError:'No errors'
});
}
});
结果显示在cansole上,所以有人可以告诉我为什么这个变量没有实例化,这个回调是异步的吗?