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
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
// 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
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.