Skip to content

Instantly share code, notes, and snippets.

@frangio
Last active April 15, 2020 03:32
Show Gist options
  • Save frangio/142fa94a5a2ddb4a4b7c74b7e9cb251f to your computer and use it in GitHub Desktop.
Save frangio/142fa94a5a2ddb4a4b7c74b7e9cb251f to your computer and use it in GitHub Desktop.
A way to use async/await in Express routes
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;
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