//get user email
let userEmail = '';
User.findOne({ _id: userId })
.then(user => {
if (!user) {
return res.status(401).json({
message: "Could not find user in database. Make sure you have an account and try again"
});
}
userEmail = user.email;
console.log('This is the email01' + userEmail);
}).catch(error => {
return res.status(500).json({
message: "Something went wrong with the server. Please try again."
});
});
console.log('This is the email' + userEmail);
由于某种原因,我可以在调用User.findOne方法时对电子邮件进行console.log记录...但是,当我尝试在函数外部访问电子邮件时,该电子邮件不再存在。请帮忙。
答案 0 :(得分:2)
不是您无法访问它,而是尚未设置。 User.findOne
调用返回一个Promise(这就是为什么您可以在其上调用.then
的原因)。当您调用findOne
时,代码将在其执行路径上继续,然后将调用console.log。但是,then
子句中的逻辑可能已经完成,也可能尚未完成(可能未完成,因为数据库调用会有一些延迟)。