Thursday 1 June 2017

How to get value from successful promise and store into external variable?

Consider my below code:

userSessionDetail.save((err, data) => {
    if (data) {
        console.log('User Session has been successfully created!');
        returnUserData = {
            username: user.username,
            sessionid: LoginUserModel.findOne({
                    email: req.body._usercredentials.email
                })
                .sort({
                    loginDateTime: 'desc'
                })
                .then((res) => {
                    // console.log(res._id) Successfully get value from promise
                    return res._id
                })
                .catch((err) => {
                    console.log(err);
                })
        }
        console.log(returnUserData.sessionid); //empty
    } else {
        console.log('While creating User Session, something went wrong.');
    }
})

What I'm trying is to get the value from my promise and put in my property value of sessionid. Above code doesn't give me the value from my promise. It shows me below results:

User Session has been successfully created! Promise { emitter:
EventEmitter { domain: null, _events: { reject: [Function] }, _eventsCount: 1, _maxListeners: undefined }, emitted: {}, ended: true }

Could you clarify how to pass the resulting 'res._id' to the value of property sessionid, and not the promise itself?



via Ahmer Ali Ahsan

No comments:

Post a Comment