Created
October 15, 2021 14:22
-
-
Save stuart-haas/a3c75dbdeb13ee3b7848bc8a152ea983 to your computer and use it in GitHub Desktop.
Express route controller async wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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