Using promises with Express.js

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());
});
Advertisements

2 thoughts on “Using promises with Express.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s