Skip to content

Instantly share code, notes, and snippets.

@poveden
Last active March 5, 2019 16:27
Show Gist options
  • Save poveden/b5ab0468b00f2b6f86767aeebeab7bcd to your computer and use it in GitHub Desktop.
Save poveden/b5ab0468b00f2b6f86767aeebeab7bcd to your computer and use it in GitHub Desktop.
Simple wrapper for promise-based Express.js middlewares.
/**
* Simple wrapper for promise-based Express.js middlewares.
* @param {function(req, res): Promise<void>} asyncHandler The promise-based middleware to wrap.
* @returns {function(req, res, next)} A middleware that can be passed to Express.js.
* @example
* app.use('/', asyncWrapper(async (req, res) => { res.send('Hello!'); }))
*/
function asyncWrapper(asyncHandler) {
return (req, res, next) => {
(async () => {
try {
await asyncHandler(req, res);
if (!res.finished) {
next();
}
} catch (err) {
next(err);
}
})();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment