0

I have several async http requests I need to make to an API to fetch some data. It's pretty simple to setup in a loop in a function like this:

async function fetchData() {

  let data = {}
  for (const asset of someAssets) {
    try {
      data[asset.id] = await library.fetchSomeData(asset.id)
    } catch (err) {
      console.error(err)
    }
  }

  return data
}

let data = fetchData()
console.log(data)

The problem here is that the last console.log(data) comes back as a pending Promise instead of the data. How do I fix this issue? Do I need to wrap my "main" code (at the bottom) in a async function as well? At what point does my entire project just need to wrapped around a async function?

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • 2
    You still need to `await` the `fetchData` function. Or use a `then`. – evolutionxbox Jan 27 '20 at 15:53
  • 1
    @VLAZ please find a better duplicate. That is a canonical question about callback-based asynchronicity, not `async` / `await` or even promises. While the answers do contain information about promises, that is a disingenuous "duplicate" for this question. – Patrick Roberts Jan 27 '20 at 15:56
  • 1
    @JakeWilson does [this](https://stackoverflow.com/q/35302431/1541563) answer your question? – Patrick Roberts Jan 27 '20 at 15:59

0 Answers0