Skip to content

Instantly share code, notes, and snippets.

@stuart-haas
Created October 15, 2021 14:22
Show Gist options
  • Save stuart-haas/a3c75dbdeb13ee3b7848bc8a152ea983 to your computer and use it in GitHub Desktop.
Save stuart-haas/a3c75dbdeb13ee3b7848bc8a152ea983 to your computer and use it in GitHub Desktop.
Express route controller async wrapper
/**
Throw uncaught errors to the next middleware automatically
and avoid having to use try/catch in the controller methods
router.get('/', asyncRequest(controller.index));
with asyncRequest...
index: async(req, res) => {
const data = await Model.findAll();
res.json(data);
}
without asyncRequest...
index: async(req, res, next) => {
try {
const data = await Model.findAll();
return res.json(data);
} catch (error) {
return next(error);
}
}
**/
const asyncRequest = (fn) => function (req, res, next) {
fn(req, res, next).catch(next);
};
module.exports = asyncRequest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment