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
app.get("/:bosskey/:mode", function(req, res) {
      res.prom(Process.reqGetKey(req));
    });

and another (handling an appEngine health check request) which is also aynchronous

// appengine health check
    app.get('/_ah/health', function(req, res) {
      res.prom(Process.ping());
    });

and one which is not, but which gets turned into an immediately resolved promise to keep the same structure

 app.get('/info', function(req, res) {
      res.prom(Promise.resolve({
        ok: true,
        code: 200,
        info: {
          api:'effex-api',
          version:'1.0'   
        }}));
      });

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.
// this is a middleware to handle promises in the router
  function prommy(req, res, next) {
    res.prom = function(prom) {
      prom.then(function(result) {
          res.json(result);
        })
        .catch(function(error) {
          res.json(error);
        });
    };
    next();
  }

Using the middleware

Injecting this into the chain of middleware, is just this
app.use(prommy);

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.