Sunday, June 5, 2011

dealing with multiple nesting callbacks in asynchronous code

If you are annoyed that you have to write multiple nesting asynchronous callback functions when you work with Node.js, you are not alone. Getting used to the asynchronous programming style and always keep in mind everything runs in the event loop is a bit tricky at the beginning.

There are many libraries and articles that addresses this nesting callback issue. This should help you to avoid those ugly pyramid shaped code now ;-)

InfoQ: how to survive asynchronous programming in JavaScript (includes a list of libraries with comparisons and Q&A from their developers)

Stackoverflow post about how to deal with the nesting callbacks (also includes a list of libraries)

Isaacs's presentation on the topic and his library Slide (he is the author of npm)

Tim Caswell (creationix)'s series on control flow in Node (II and III can be found on the right column, other articles by the same author)

CommonJS Promises is another way trying to address this issue by defining a standard interface for interacting with the result object of asynchronous actions. Roughly speaking, a promise object is a placeholder for the value for the asynchronous action. And you can treat is as normal object, assign values to another variable, pass it around, etc. Right now, FuturesJS implements this and it is not solely for server-side JS. dojo.Deferred is another similar effort. This SitePen blog post has some easier to understand coverage about the promises.

StratifiedJS extends the JavaScript language to achieve similar goals of allowing asynchronous control flow to be expressed in a synchronous way. Very neat work indeed. This is a short overview presentation about it.