Previous month:
April 2011
Next month:
June 2011

May 2011

Avoiding Asynchronous Programming in Node.JS

Node.js is supposed to be all about an asynchronous style of programming. Rather than executing functions and getting results, we use a lot of first order functions and callbacks to do things asynchronously. Here's an example of this style from the djangode project. makeApp is a function that takes an array of arrays that are regex/function pairs. Some of those function invoke other functions (such as setTimeout) that take other functions.

I find this kind of code rather tricky to test, and to reason about. Functions nested four levels deep makes my spidey-sense tingle. A good technique for cleaning it up can be extracting those anonymous functions into named functions, but if there are variables that are shared across scopes, that can get a little messy too.

However, I really like Node.js and the approach they've taken, simply because the asynchronous style is a rather elegant (if not new) solution to the kind of performance problems you encounter when working with single threaded code. Blocking operations, IO is particular, can really kill your app, and using threads to avoid blocking can lead to code that is nigh-impossible to test or reason the Node.js asynchronous style merely being a bit tricky is a huge upgrade.

However, I haven't found myself really digging using that style all the time. I generally prefer a functional style when working in JavaScipt. In my opinion, function composition is a huge advantage in JavaScript, but callbacks generally don't have return values, so they're harder to compose. In fact, it really only seems appropriate to use callbacks when I would otherwise be tempted to use a thread to avoid onerous blocking IO. Otherwise, I like to stick a more functional style and stay away from the asynchronous code.