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)

Not the promised land

Promises are a much touted solution to callback hell in nodejs. They can certainly help to clean up your code, taking you from this:

doSomething(function(err, res) {
    if (err) {
        return handleError(err);
    }

    doSomethingElse(res, function(err, res2) {
        if (err) {
            return handleError(err);
        }

        andThen();
    });
});

to this:

doSomething().then(function(res) {
    return doSomethingElse(res);
}).then(function() {
    andThen();
}).fail(handleError);

A definite improvement! However, there is a subtle difference between using callbacks and using promises: an unhandled error in the callback code will blow up the event loop, but can be swallowed by the promises (specifically, if you don’t provide a fail handler, or call done).

I want my software to fail fast (“let it crash”), rather than limping onwards. Unfortunately, this means that you need to be very careful when using promises, to ensure that you have covered all the possible cases. And it means you need a good understanding of how they work before starting to use them; not exactly the pit of success.

So, do the readability benefits outweigh the consequences? I think so, for now, but there’s definitely room for improvement. Maybe generators will be that silver bullet :)