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.
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
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.
Injecting this into the chain of middleware, is just this
The code for the entire application can be found here
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > React, redux, redis, material-UI and firebase >