Muhib Ahmed
Muhib Ahmed

Reputation: 331

Why this promisified JWT.verify isn't working?

So I'm trying to promisify jwt.verify manually but for some reason it is not passing the decoded_token to the resolve function.

This is working fine... enter image description here

This isn't.. enter image description here

PromisifiedJWTVerify.. enter image description here Can someone please mention the cause of this behavior?

Upvotes: 0

Views: 2124

Answers (2)

imadeddine bouzair
imadeddine bouzair

Reputation: 11

The solution of your problem is this:

const promisefyJWTToken = (token) => {
  return new Promise(function (resolve, reject) {
    if (token) return resolve(jwt.verify(token, process.env.JWT_KEY));

    return reject('Invalid Token');
  });
};

Upvotes: -1

destroyer22719
destroyer22719

Reputation: 404

you need to use invoke resolve() like that on jwt.verify(token, secret, resolve), when you just do resolve you aren't invoking it, you're referencing it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

edit: Screw my answer above I think it's supposed to be like this

jwt.verify(token, secret, (err, data) => {
  if (err) return reject(err);
  return resolve(data);
});

this is because the first parameter passed in the callback is the error, which you don't want to put in the resolve but in the reject while the second parameter is the actual data which in case you actually do want in resolve

https://www.npmjs.com/package/jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback

Upvotes: 2

Related Questions