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
6
Upvotes
View all comments
Show parent comment
1
u/[deleted] Feb 11 '12
I think what I will do is a hybrid of the labels approach and the callback approach, allowing the user to choose whichever approach they like.
So you'll be able to do any of the following:
1.
2.
3.
4.
Of course, (4) gives the very most debugging info and protection, at the cost of more boilerplate.