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 :)

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