节点 promisify、await 和 return 回调属性

Node promisify, await and return callback properties

有没有一种方法可以转换 jsonwebtokenverify 方法,使其以这种方式工作?

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

我已经设法将它转换为一个承诺,但是我想使用 .then,但是我不想这样做。当前 errdecoded 未定义。

这是完整的代码,可以这样做吗?

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);
  }

创建您自己的 verify 函数。

import jwt from 'jsonwebtoken';
import util from 'util';
const jwtPromise = util.promisify(jwt.verify);
const secret = 'shhhhh';
const wrongSecret = '123';

const token = jwt.sign({ foo: 'bar' }, secret);

export const store = async () => {
  const r = await verify(token, secret);
  console.log(r);
};

store();

function verify(token, secret) {
  return jwtPromise(token, secret)
    .then((decoded) => ({ err: null, decoded }))
    .catch((err) => ({ err, decoded: null }));
}

验证正确输出:

{ err: null, decoded: { foo: 'bar', iat: 1619006803 } }

验证失败输出:

{
  err: JsonWebTokenError: invalid signature
      at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/jsonwebtoken/verify.js:133:19
      at getSecret (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/jsonwebtoken/verify.js:90:14)
      at module.exports (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/jsonwebtoken/verify.js:94:10)
      at internal/util.js:297:30
      at new Promise (<anonymous>)
      at internal/util.js:296:12
      at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/67195388/index.ts:10:19
      at Generator.next (<anonymous>)
      at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/Whosebug/67195388/index.ts:8:71
      at new Promise (<anonymous>),
  decoded: null
}

err 和 decoded 在第三个参数中作为回调传递给验证函数:

jwt.verify(token, secretKey, (err, decoded) => {
    console.log(err, decoded);
    ...
});

您可以将任何异步函数转换为您想要的return。您可以通过将其包装在另一个函数中来做到这一点,该函数 return 是一个承诺,而不是在出现错误时拒绝总是解析为包含错误和结果键的对象。

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)
        })
    }
}