0

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.

2
  • I understand that you want to find a simple coffee-ish way. I'm afraid there is no way (yet), maybe some day with generators of ES6. But BTW isn't it possible to concat the SQL an do a bulk insert? Is this MySQL? And I wouldn't bother using async or Seq when doing server-side programming. It's more readable to other node.js programmers than detecting what you want to achieve with constructs like if i == stores.length - 1. Commented Feb 24, 2014 at 21:43
  • "But BTW isn't it possible to concat the SQL an do a bulk insert?" yes, but I can just as easily ask this question for other async operations that don't concatenate well. Commented Feb 24, 2014 at 21:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, yeah, that is what I asked for. I'm looking for a native solution. I want to know if there is a better way to do this without bringing in a library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.