r/coffeescript • • Feb 11 '12
DelayedOp - five handy, tiny lines of CoffeeScript
Edit: I've expanded this. Now includes debugging features, more informative errors per almost's suggestions.
I wrote a class recently that I thought I'd share because I was struck by how elegantly it came across in CoffeeScript.
The idea here is that it's a fairly common scenario to make a few asynchronous calls at the same time, and
then want to do something once all of them have finished. This is easy with the DelayedOp class.
Here it is:
class DelayedOp
constructor: (@callback) -> @count = 1
wait: => @count++
ok: => @callback() unless --@count
ready: => @ok()
And an example of it in action using jQuery:
op = new DelayedOp -> alert 'Done loading'
op.wait() #wait to receive data from foo.cgi
$.getJSON 'foo.cgi', (data) ->
doSomethingWith data
op.ok()
op.wait() #wait to receive data from bar.cgi
$.getJSON 'bar.cgi', (data) ->
doSomethingElseWith data
op.ok()
op.ready() # Finalize the operation
7
Upvotes
View all comments
Show parent comment
1
u/red_hare Apr 09 '12
I think everyone hits this problem sometime early in learning JavaScript, but most of our solutions aren't so elegant (mine wasn't atleast). This is actually very similar to what icedcoffeescript compiles to, except it lacks the nice class wrapping. I prefer this by far