Last active
March 5, 2019 16:27
-
-
Save poveden/b5ab0468b00f2b6f86767aeebeab7bcd to your computer and use it in GitHub Desktop.
Simple wrapper for promise-based Express.js middlewares.
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
/** | |
* 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