Search code examples
javascriptnode.jsasynchronouscoffeescript

Waiting on all CallBacks to finish executing without a static time


I've been working an express application recently and I've been using CoffeeScript to make the JS a bit more bearable. I have a structure similar to the following:

items = []
for region in regions
    expensive_function {}, (err, data) ->
        # operations on data/error handling
        items.push({k: data['v'][a]['l']}) # transforming information from data
return items

The items array invariably comes out empty after that return, which I have a feeling may be a race condition due to the normal NodeJS async.

I need to go through all items in the regions array and getting the data from that expensive function before I can return.

Any suggestions?


Solution

  • You can turn the expensive_function into a promise returning function, and use async/await:

    expensive_function_promise = (obj) ->
      return new Promise (resolve, reject) ->
        expensive_function obj, (err, data) ->
          reject(err) if err?
          resolve data
    
    create_items = (regions) ->
      items = []
      for region in regions
        data = await expensive_function_promise {}
        items.push { k: data.v[a].l }
      items
    
    create_items regions
      .then (items) ->
        do_something_with items
      .catch (err) ->
        handle_error err