When using the Express router, the usual sequence of events is to detect the route, examine the request, perform some action, then send back the response. It’s quite likely that the action to be performed is asynchronous, so that’s better done with promises than a potentially confusing series of callbacks. I was working on a generic way of handling promises as middleware, and came across this post.  I’ve tweaked that a little and here’s the final result.

Handling a route

I’m using a standard way of handling a route, and don’t need to care if it’s asynchronous or not.
Here’s an example route whose action is asynchronous, and returns a promise to its completion
and another (handling an appEngine health check request) which is also aynchronous
and one which is not, but which gets turned into an immediately resolved promise to keep the same structure

The middleware

In Express.js you can use middleware to incrementally process a request, so the res.prom method has been implemented as middleware as follows, which takes care of stringifying and sending the result when completed.

Using the middleware

Injecting this into the chain of middleware, is just this

Source code

The code for the entire application can be found here

For more like this, see React, redux, redis, material-UI and firebase. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.