我很确定这里的问题只是我没有为Node.js以必要的异步方式思考。
我在模块userExists()
中有一个函数db
,它在传递电子邮件时检查用户是否在数据库中,并返回true
或false
。
相关部分:
userExists : function(email) {
var client = new pg.Client(app.conString);
var query;
var result = false;
client.connect();
query = client.query(
"SELECT * FROM users WHERE email = $1",
[email]
);
query.on('row', function(row) {
result = true;
});
query.on('end', function() {
client.end();
return result;
});
我这样称呼它:
if (!db.userExists(req.session.email)) {
newUser();
} else {
updateUser();
}
}
无论newUser()
返回什么,它都会被调用userExists()
。我该如何解决这个问题?
答案 0 :(得分:1)
你错了。运行函数后查询结束,因此您需要传递回调函数并“等待”结果。
userExists = function(email, cb) {
var client = new pg.Client(app.conString);
var query;
var result = false;
client.connect();
query = client.query(
"SELECT * FROM users WHERE email = $1",
[email]
);
query.on('row', function(row) {
result = true;
});
query.on('end', function() {
client.end();
cb(result);
});
}
// Time 1: ask is the user exists
db.userExists(req.session.email, function(exists) {
// Time 3: Yeah result came back
if (exists) {
updateUser()
}
else {
newUser();
}
});
// Time 2: I've asked, let's wait for the result
// The following code will likely be executed before you get the result back