Last Updated: February 25, 2016
·
6.157K
· dyscrete

Using IcedCoffeescript to mitigate callback headaches

IcedCoffeeScript is a fairly new superset of CoffeeScript that adds 2 new keywords: await and defer. Iced comes with a drop-in replacement interpreter iced.

In 140 characters or less: IcedCoffeescript makes event based programming easier with a procedural-like syntax.

The await block allows you to run multiple asynchronous calls in parallel, and precede when their defer callback is fired.

Example

Here are some examples of await and defer in action.

Edit: I feel my previous example failed to show the big picture. Here's a much dirtier example of deferring with IcedCoffeeScript

IcedCoffeeScript

search = (keyword, cb) ->
   host = "http://search.twitter.com/"
   url = "#{host}/search.json?q=#{keyword}&callback=?"
   await
      $.getJSON url, defer json
      logSearch keyword, defer success
   cb json.results

CoffeeScript equivalent

search = (keyword, cb) ->
   host = "http://search.twitter.com/"
   url = "#{host}/search.json?q=#{keyword}&callback=?"

   deferred = 0
   json = null
   success = null

   next = ->
      cb json.results
   defer = (next) ->
      next() if ++deferred is 2

   $.getJSON url, (_json) ->
      json = _json
      defer()
   logSearch url, (_success) ->
      success = _success
      defer()

Source: nodewebdesign.com

1 Response
Add your response

Nice one. After using IcedCoffeeScript for a few months, now I can't even imagine writing Node.js apps without it. I'd like to see more developers using it, as it elegantly mitigates one of the major drawbacks of Node.js.

I've recently published a similar pro tip showing a "real world" usage scenario.

over 1 year ago ·