How to get variable's value outside promise? : <p>I'm trying to set a value to a variable outside a promise.
But when I check the value it prints <code>undefined</code>,
I defined the variable outside the promise so I don't understand why its <code>undefined</code></p>

<p>Here is my code, hope you can help me with that:</p>

<pre><code>UserSchema.statics.findByToken = function (token) {
var User = this;
var decoded;

try{
    decoded = jwt.verify(token, 'secret');
} catch (err){

    if(err.name === 'TokenExpiredError'){

        var refreshToken;

        User.findOne({
            'tokens.token': token,
            'tokens.access': 'auth'
        }).then( (user) =&gt; {

            User.findOne({
                'tokens.token': token,
                'tokens.access': 'auth'
            }).then( (user) =&gt; {
                var access = 'auth';
                token = jwt.sign({_id: user._id.toHexString(), access}, 'secret', { expiresIn: 30 }).toString();

                refreshToken = token; // set value to refreshToken

                user.tokens.push({access, token});

                user.save().then( () =&gt; {
                     token = refreshToken;
                });
            });
        });


        console.log(refreshToken);  // refresh is undefined
        return Promise.reject({errName: 'TokenExpiredError', token: refreshToken});

    }

    return Promise.reject();

}

    return User.findOne({
       _id: decoded._id,
       'tokens.token': token,
       'tokens.access': 'auth'
    })
}
</code></pre>
