Reputation: 46613
Say I want to insert a group of Store records into the database and call a callback when they are all complete:
insertStores = (db, stores, callback) ->
sql = ""
processed = 0
for store in stores
do (store) ->
# build sql
sql = "some built sql goes here"
processQuery(db, sql, ->
++processed
if processed >= stores.length
callback?()
)
I'm wondering if there's a more readable way to do this that will get rid of the processed
variable. It's important that all inserts get processed before the callback is fired. I don't want to bring in any async to sync libraries. This is for a script, not an application.
Is there a better way to do this in coffeescript? I'm wondering if there's an elegant coffee-ish solution that I'm not aware of.
Upvotes: 0
Views: 49
Reputation: 11218
Do you specifically need a CoffeeScript way of doing this? I think the Async package would be a good thing to use. It has a number of functions to let you run asynchronous tasks in series or parallel and get a single callback when everything is finished.
Upvotes: 1