knowledge › JavaScript

Async/Await in Express

Original route handler

router.get('/user/:id', async (req, res, next) => {
  try {
    const user = await getUser({ id: req.params.id });
    res.json(user);
  } catch (e) {
    // will eventually be handled by error handling middleware
    next(e); 
  }
});

Since Async Await is essentially syntactic sugar for promises, and if an await statement errors it will return a rejected promise, we can write a helper function that wraps our express routes to handle rejected promises.

function asyncMiddleware(fn) {
  return (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}

Complete example importing async middleware

const asyncMiddleware = require('./asyncMiddleware');

router.get('/users/:id', asyncMiddleware(async (req, res, next) => {
  const user = await getUserFromDb({ id: req.params.id });
  res.json(user);
}));

Snippet from Using Async Await in Express with Node 11