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


Content properties

  • Type: Note
  • Category: JavaScript
  • Tags: frontend, javascript
  • Custom slug: None

This is a preview of a simpler page design that I'm working on over the next little bit. I've finally added a (click it!) but there's still a few pages left to be converted so don't worry if things don't look quite right just yet 🙏

Content on blog pages use the CC-BY-SA license. The source code and notes use the MIT license. Unsure? Mention me on Mastodon.