无法访问函数外部的变量

时间:2020-10-07 23:43:21

标签: javascript node.js mongoose

//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记录...但是,当我尝试在函数外部访问电子邮件时,该电子邮件不再存在。请帮忙。

1 个答案:

答案 0 :(得分:2)

不是您无法访问它,而是尚未设置。 User.findOne调用返回一个Promise(这就是为什么您可以在其上调用.then的原因)。当您调用findOne时,代码将在其执行路径上继续,然后将调用console.log。但是,then子句中的逻辑可能已经完成,也可能尚未完成(可能未完成,因为数据库调用会有一些延迟)。

相关问题