node-async-router
is a wrapper around router
that adds
support for ES2016/ES7 async functions. It can
be used as a drop-in replacement for Express' default router, as well as for other middleware-based
frameworks.
Requires node 8+ for async/await support, or something like Babel.
var app = require('express')(),
router = require('node-async-router')();
router.get('/users/:username', async function(req, res, next) {
var user = await UserModel.find({ username: req.params.username });
res.json(user);
});
app.use(router);
app.listen(3000);
$ npm install node-async-router
node-async-router
is a thin wrapper around the router
module. Aside from adding support for async functions as middleware, it remains 100% compatible
with the preexisting router
API.
In short, node-async-router
lets you pass in an async function anywhere that router
accepts
a "normal" function as a middleware/handler definition. More specifically, the following router
APIs are supported:
router.use([path], ...middleware)
router[method](path, ...[middleware], handler)
router.param(name, param_middleware)
route[method](handler)
route.all(handler)
The API surface is well tested, but please do report any issues if you see them!
Error handling behaves the same as in the router
module,
with the exception that if an async function is used and it resolves to a rejection/error, then that
error is automatically passed on to next()
.
Example:
var app = require('express')(),
router = require('node-async-router')();
router.get('/500-me', async function(req, res, next) {
var err = new Error();
// option 1: use next()
return next(err);
// option 2: throw it
throw err;
// option 3: await on a rejected promise (without catching it)
var user = await Promise.reject(err);
});
router.use(function(err, req, res, next) {
console.error('Unhandled error:', err);
res.status(500).send('My bad!');
});
app.use(router);
app.listen(3000);