gallowaystorm
gallowaystorm

Reputation: 21

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. Please help.

Upvotes: 0

Views: 210

Answers (1)

MikeTheReader
MikeTheReader

Reputation: 4190

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). When you call findOne the code continues on its execution path, which will then call your 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).

Upvotes: 2

Related Questions