userqwert userqwert - 1 year ago 55
Node.js Question

bluebird node promises, cant resolve value

I'm trying to write some promises in my express application using bluebird, but have run into a problem. How do I access the

user
value here - it is not being returned by the
resolve(response)
method.

This is the routes file:

router.get('/auth/google/callback', (req, res) => {

google.getToken(req.query.code)
.then( () => { google.getUser() })
.then(user => {
console.log(user); //undefined - response is NOT defined here
})
});


This is the file to manage authentication from which the methods are exported.

module.exports.getToken = (code)=> {
console.log('step 1');
return new Promise((resolve, reject) => {

oauth2Client.getToken(code, (err, tokens) => {
if (!err) {
oauth2Client.setCredentials(tokens);
resolve();
}

});

});

};

module.exports.getUser = () => {
console.log('step 2');
return new Promise((resolve, reject) =>{

plus.people.get({
userId: 'me',
auth: oauth2Client
}, (err, response) => {
if(!err)
resolve(response); //response is defined here as the user
else
reject(err);
});
});
};

Answer Source

You appear to be chaining the .then in your routes file off of the wrong method, if you are expecting google.getUser() to return the value you want to store in user you should chain the .then on the end of that function call.

router.get('/auth/google/callback', (req, res) => {

    google.getToken(req.query.code).then( () => { 

        google.getUser().then(user => {
            console.log(user); //undefined - response is NOT defined here
        }); //End getUser().then(..)

    }); //End getToken.then(..)

}); //End router.get(..)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download