I was looking for a way to combine promises with Express. I found a few suggestions, like this middleware, but nothing that really fit what I wanted.
Ideally, I’d like to be able to just return a promise from a handler:
app.get("/foo", function(req, res) { return getSomethingAsync(); });
but I couldn’t see any way to achieve that without hacking on express itself. The best I could come up with was some middleware to add a method to the response:
module.exports = function() { return function(req, res, next) { res.promise = function(promise) { promise.then(function(result) { res.send(200, result); }).fail(function(err) { if (err.statusCode) { res.send(err.statusCode, { error: err.message }); } else { res.send(500, { error: 'Unexpected error' }); } }).done() }; next(); }; };
which can be used like this:
app.get("/bar", function(req, res) { res.promise(getSomethingAsync()); });
Try this https://github.com/alex-whitney/express-promise-router