Created
August 2, 2019 00:51
-
-
Save Arsfiqball/17d47bba6bc269b25df883ec3933a334 to your computer and use it in GitHub Desktop.
Wrap async function to express compatible middleware
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
// wrapper function | |
function wrap (fn) { | |
return function (req, res, next) { | |
return fn(req, res, next).catch(err => { | |
// handle general error here | |
next(err) | |
}) | |
} | |
} | |
// usage as express middleware | |
app.use(wrap(async function (req, res, next) { | |
const users = await req.db('users') | |
res.status(200).json({ users }) | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment