[英]Can't access variable outside of function
//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 email...但是,当我尝试在 function 之外访问它时,它不再存在。 请帮忙。
不是你不能访问它,而是它还没有被设置。 User.findOne
调用返回 Promise(这就是为什么您可以调用.then
的原因)。 当您调用findOne
时,代码会继续其执行路径,然后调用您的 console.log。 然而, then
子句中的逻辑可能已经完成也可能没有完成(可能没有,因为数据库调用会有一些延迟)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.