Last active
April 15, 2020 03:32
-
-
Save frangio/142fa94a5a2ddb4a4b7c74b7e9cb251f to your computer and use it in GitHub Desktop.
A way to use async/await in Express routes
This file contains hidden or 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
const express = require('express'); | |
const methods = require('methods'); | |
function AsyncRouter(options) { | |
const router = express.Router(options); | |
Object.setPrototypeOf(router, AsyncRouter.prototype); | |
return router; | |
} | |
Object.setPrototypeOf(AsyncRouter.prototype, express.Router); | |
const catchAsyncError = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); | |
for (const method of methods.concat('all')) { | |
AsyncRouter.prototype[method] = function (path, ...fns) { | |
return express.Router[method].call(this, path, ...fns.map(catchAsyncError)); | |
} | |
} | |
AsyncRouter.prototype.use = function (pathOrFn, ...fns) { | |
const wrappedPathOrFn = typeof path === 'function' ? catchAsyncError(path) : path; | |
return express.Router.use.call(this, wrappedPathOrFn, ...fns.map(catchAsyncError)); | |
} | |
module.exports = AsyncRouter; |
This file contains hidden or 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
const AsyncRouter = require('./async-router'); | |
const express = require('express'); | |
const routes = new AsyncRouter(); | |
routes.get('/', async (req, res) => { | |
res.send(await Promise.resolve('hello world')); | |
}); | |
const app = express(); | |
app.use(routes); | |
app.listen(3000); | |
console.error('listening on http://localhost:3000'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment