Search code examples
javascriptobjectpromisestrapi

JS Promise resolve object


The following method verifies JWT and returns id and expiration.

verify(token, secret = "jwtSecret") {
    console.log("verify jwt: ", secret);
    return new Promise(function (resolve, reject) {
        jwt.verify(
            token,
            _.get(strapi.plugins, ['users-permissions', 'config', secret]),
            {},
            function (err, tokenPayload = {}) {
                if (err) {
                    return reject(new Error('Invalid token.'));
                }
                console.log(tokenPayload);
                resolve(tokenPayload);
            }
        );
    });
},

When I call verify, I am expecting to return the following object

Promise { { id: 77, iat: 1593603153, exp: 1596195153 } }

But I am unable to access the id of the object.

When I am doing console.log("user id: ", payload.id), the payload.id is showing up as undefined in console.

async refreshToken(ctx) {
    const { token } = ctx.request.body;
    const payload = strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec");
    console.log("auth: ", payload); // this log ->  Promise { { id: 77, iat: 1593603153, exp: 1596195153 } } 
    console.log("user id: ", payload.id); // this log -> undefined
    return data;

},

Solution

  • As Andreas suggested, it would be advisable to review how promises work.

    From MDN:

    The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

    A Promise is a proxy for a value not necessarily known when the promise is created.

    In your first case (console.log("auth: ", payload);), the console.log function knows that it should print the value of the promise once it receives it.

    In the 2nd case, (console.log("user id: ", payload.id);), the promise hasn't resolved by the time you try access the id property of the result.

    There's 2 ways to resolve this issue.

    Method 1: Using then

    refreshToken(ctx) {
        const { token } = ctx.request.body;
        const payload = strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec")
            .then(payload => {
                console.log("auth: ", payload); // this log ->  { id: 77, iat: 1593603153, exp: 1596195153 }
                console.log("user id: ", payload.id); // this log -> 77
                return data;
            });
       
    },
    

    Method 2: ES2017 Aysnc/Await

    async refreshToken(ctx) {
        const { token } = ctx.request.body;
        const payload = await strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec");
        // Will wait for promise to resolve before continuing with await above
        console.log("auth: ", payload); // this log ->  { id: 77, iat: 1593603153, exp: 1596195153 }
        console.log("user id: ", payload.id); // this log -> 77
        return data;
    
    },