09 7 / 2010
defer: Taming Asynchronous JavaScript with CoffeeScript
Tim Cuthbertson has written an extension to CoffeeScript called defer, which is a way of writing asynchronous javascript in a more straightforward and synchronous-looking way. It adds a language feature called Continuations, which are objects that represent “the rest of the currently executing program”. In other words, a continuation represents all of the code after an asynchronous operation like an AJAX request.
Basically, instead of writing code with callbacks as it is traditionally done in JavaScript which often lead to cluttered code, you can write it as if it were entirely synchronous, except with the new defer keyword.
For example, you would currently write code like this:
database.get("test", function(result) {
//do stuff
})
And with the new defer keyword, it is simplified to this:
var result = defer database.get("test");
//do stuff
However, the call to the database actually remains asynchronous since the compiler generates the callbacks for you. This could really help to clean up a lot of the asynchronous code mess that we are dealing with more and more when using things like Node.js, which contains entirely asynchronous I/O. Since Tim has written this on top of CoffeeScript, you get additional awesome features like array comprehensions, and true classes for your code as well. If you haven’t checked out CoffeeScript yet, be sure to do so.
I think that with more and more asynchronous I/O going on, something like this will be necessary to try to deal with all of the callbacks and messy looking code that will inevitably be produced. This is just one implementation. We have seen things like NarrativeJS and JavaScript Strands before, which are entirely in JavaScript and take a different approach to the problem. Maybe at some point, JavaScript will have the feature baked right in, but until then, using a compiler to help work out the problem is perfectly valid.
Nice work, Tim! There is an extensive write up about this work on Tim’s blog for you to check out, as well as his CoffeeScript fork on Github. Be sure to follow this closely. I’m sure it will go great places!