Search code examples
node.jsjwtes6-promise

Node promisify, await and return callback properties


is there a way I can convert the jsonwebtoken package verify method so it works in this way?

const { err, decoded } = await jwtPromise(post.journey_token, 'test');

I have managed to convert it to a promise, but this want's to use .then, however I don't want to do it this way. Currently err and decoded is undefined.

Here is the full code, can this be done?

import jwt from 'jsonwebtoken';
import util from 'util';

export const store: APIGatewayProxyHandler = async ({body}) => {
  const post = JSON.parse(body);
  const jwtPromise = util.promisify(jwt.verify);

  if (post.journey_token) {
    const { err, decoded } = await jwtPromise(post.journey_token, 'test');
    console.log(decoded, err);
  }

Solution

  • You can convert any asynchronous function to return what you want. You can do so by wrapping it in another function which returns a promise, which instead of rejecting in case of an error always resolves to an object containing both an error and a result key.

    function promisify(asyncFunction) {
        return function (...args_) {
            return new Promise(function (resolve, reject) {
                function cb(error, result) {
                    resolve({ error, result })
                }
                var args = [
                    ...args_,
                    cb
                ]
                asyncFunction(...args)
            })
        }
    }