简体   繁体   English

无法访问 function 之外的变量

[英]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);

For some reason, I can console.log the email when calling in the User.findOne method... however, when I try to access it outside of the function, it no longer exists.出于某种原因,我可以在 User.findOne 方法中调用 console.log email...但是,当我尝试在 function 之外访问它时,它不再存在。 Please help.请帮忙。

It's not that you can't access it, it's that it hasn't been set yet.不是你不能访问它,而是它还没有被设置。 The User.findOne call returns a Promise (which is why you can call .then on it). User.findOne调用返回 Promise(这就是为什么您可以调用.then的原因)。 When you call findOne the code continues on its execution path, which will then call your console.log.当您调用findOne时,代码会继续其执行路径,然后调用您的 console.log。 However, the logic within the then clause may or may not have completed (likely not, since there will be some latency with the database call).然而, then子句中的逻辑可能已经完成也可能没有完成(可能没有,因为数据库调用会有一些延迟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM