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
Interesting. So the generated
okcallback could automatically throw an exception if it were called more than once.My only problem with that is that it's more boilerplate and another indentation level. I'm hesitant to wrap things in yet another layer of anonymous function, especially because I'd like this to be plain-JS friendly. I'm going to work on some of these other ideas while I mull this over.