我正在使用Express和postgreSQL数据库使用node-postgres编写Node.js应用程序。我想根据他们的电子邮件查找当前用户的用户名和真实姓名,并在req.session中设置它们。但是,如果我将它们设置在下面代码中的位置,那么当我们离开该块时它们是未定义的(即第一个console.log语句打印正确的信息,第二个组打印未定义。我该如何解决这个问题?
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
console.log(req.session.realname);
console.log(req.session.username);
});
console.log(req.session.realname);
console.log(req.session.username);
query.on('end', function() {
client.end();
});
答案 0 :(得分:1)
第二对console.log
将在查询结果可用之前执行(在row
事件处理程序中)。
如果您的代码将用于Express路线,您可以使用以下内容:
app.get('/', function(req, res) {
var client = new pg.Client(app.conString);
var realname = "";
var username = "";
client.connect();
var query = client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email]
);
query.on('row', function(row) {
req.session.realname = row.realname;
req.session.username = row.username;
});
query.on('end', function() {
client.end();
res.send(...); // <-- end the request by sending back a response
});
});
使用node-postgres
的EventEmitter接口的另一种方法是将回调传递给query
(使用Express IMHO看起来更好):
client.query(
"SELECT * FROM users WHERE email = $1;",
[req.session.email],
function(err, results) {
if (err)
// handle error
else
if (results.length)
{
req.session.realname = results[0].realname;
req.session.username = results[0].username;
}
res.send(...); // done
});