Home Waiting on all CallBacks to finish executing without a static time
Reply: 1

Waiting on all CallBacks to finish executing without a static time

Mark
1#
Mark Published in 2018-01-11 04:37:15Z

This question already has an answer here:

  • How do I return the response from an asynchronous call? 26 answers

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?

elclanrs
2#
elclanrs Reply to 2018-01-11 04:49:27Z

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
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.341408 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO