express router wrap async function


Use Try ... Catch ...

用try..catch...在express的router里使用async/await,使其可以正常抛出错误,并有错误路由处理中间件处理。

import express from 'express';
import { getOneStaff } from '../lib/staffMongoose';

const router = new express.Router();

router.use(async (req, res, next) => {
  try {
    let staffInfo = await getOneStaff(req.query.staffID);
  } catch (err) {
    next(err);
  }
});

export default router;
import express from 'express';
import { getOneStaff } from '../lib/staffMongoose';

const router = new express.Router();

router.use((req, res, next) => {
  (async () => {
    try {
      let staffInfo = await getOneStaff(req.query.staffID);
    } catch (err) {
      next(err);
    }
  })();
});

export default router;

Use Custom WrapFunction

给async函数进行捆绑, 使其抛出的错误被catch捕获到,并由next函数将error传给错误处理路由来处理。

import express from 'express';
import { getOneStaff } from '../lib/staffMongoose';
/*
 * 等价于 
 * const asyncWrap = asyncFunction => (...args) => asyncFunction(...args).catch(args[2]);
 */
const asyncWrap = asyncFunction => (req, res, next) => asyncFunction(req, res, next).catch(next);

const router = new express.Router();
router.use(asyncWrap(async (req, res, next) => {
  let staffInfo = await getOneStaff(req.query.staffID);
}));

export default router;