The promise handler

Continuing from my last adventures with promises and express.js, it turns out I can have what I want. Sort of. Behold the promise handler:

module.exports = function(inner) {
    this.handle = function(req, res) {
        res.promise(inner.handle(req));
    };
};

So now my express handlers look like this:

module.exports = function() {
    this.handle = function(req) {
        return somethingThatReturnsAPromise();
    };
};

And you would wire it all together like this:

var app = express();
app.use(promiseMiddleware());
app.get("/foo", function(req, res) {
    var handler = new PromiseHandler(new FooHandler());
    return handler.handle(req, res);
});

(As a side-note, I’m a huge fan of the Russian doll model of composing behaviour of handlers)

Advertisements

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