Skip to content

A zero-boilerplate solution for using ES7 async functions in Express and other middleware-based web frameworks.

License

Notifications You must be signed in to change notification settings

jmar777/node-async-router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

node-async-router

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.

Quick Example (Express)

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);

Installation

$ npm install node-async-router

Documentation

Overview

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.

Features

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:

The API surface is well tested, but please do report any issues if you see them!

Error Handling

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);

License

MIT

About

A zero-boilerplate solution for using ES7 async functions in Express and other middleware-based web frameworks.

Resources

License

Stars

Watchers

Forks

Packages

No packages published