Recently while working on a Backbone.JS/jQuery/CoffeeScript project, I found myself in a mess of callback and timing issues. I needed to wait for something to complete before proceeding and found myself in a mess of nested callbacks ... which is confusing and hard to debug. Then I found 2 possible solutions jQuery deferred or IcedCoffeeScript
IcedCoffeeScript
looks really easy, simply adding await
& defer
. However, I wonder if its there to stay? Only 2 questions here on StackOverflow? Not much talk about it compared to CoffeeScript
Another thing is whats the difference between the 2 methods, they seem to do mostly the same thing? Except in IcedCoffeeScript, it looks more like procedural code, and in jQuery deferred, it doesn't solve my mess of callbacks as much
The jQuery. Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred.
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
These are very different technologies:
IcedCoffeeScript is a precompiler that extends CoffeeScript with the await
and defer
keywords that transform code for you so that you can write code in a synchronous style. In the generated JavaScript, await
and defer
produce nested functions.
jQuery Deferred (aka Promises) are a way of side-stepping callbacks altogether: Instead of taking a callback, an async function can return a Promise. You then attach callbacks to the Promise. It's a simple, but powerful technique. I devote a chapter to it in my book, Async JavaScript.
Each of these technologies works best with a certain kind of API. await
and defer
expect a function to take a single callback as its last argument. Promises work best when you have lots of other Promises in your app.
There's no magic bullet for dealing with async behavior in JavaScript. You need to understand callbacks, Promises, and PubSub (aka EventEmitter
s) and choose the best tool for each job. Even if you use IcedCoffeeScript (which is cool), there are still times when Promises will save you a huge amount of work.
I hope that helps. Check out my book, Async JavaScript, for much more information.
I think IcedCoffeeScript is here to stay.
I plan on supporting it indefinitely, and am pretty regular in patching it against the mainline. I use it on almost all of my personal projects, and the site Combosaurus.com, an OkCupid Labs project just about to hit general release, is written in IcedCoffeeScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With