6

Async/await has come in handy when fetching data asynchronously, especially in the

async componentDidMount() {
    try {
       const response = await axios.get(endpoints.one)
       const data = await response
       this.setState({ data, isLoading: false })
    } catch (e) {
       this.setState({ errors: e.response })
    }

}

Moreover, when fetching from multiple endpoints, one can easily use

Promise.all([
  fetch(endpoints.one),
  fetch(endpoints.two),
]).then(([data1, data2]) => {
  console.log(data1, data2)
}).catch((err) => {
  console.log(err);
});

However, how can one use aync/await to fetch data from multiples sources instead of Promise.all?

Erick Mwazonga
  • 1,020
  • 12
  • 25
  • You can await ```Promise.all()```. See [this question](https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel) – Chris B. May 15 '19 at 15:45
  • some answers from here provide solutions without `Promise.all`: https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel – Andrey May 15 '19 at 15:46
  • you can simply await Promise.all() – GifCo May 15 '19 at 15:46

1 Answers1

12

If you want to do them in parallel, then you'll still Promise.all. Just you'll await the result rather than calling .then

async someFunction() {
  try {
    const [data1, data2] = await Promise.all([
      fetch(endpoints.one),
      fetch(endpoints.two),
    ]);
    console.log(data1, data2);
  } catch (err) {
    console.log(err);
  }
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • A good idea, however when you are doing it the componentDidMount.... `async componentDidMount() { someFunction() }` you do not get data in the response – Erick Mwazonga May 15 '19 at 16:12
  • Are you referring to the fact that i didn't have a return statement in my example? – Nicholas Tower May 15 '19 at 16:23
  • @ErickMwazonga what do you mean by "you do not get data in the response"? are you just referring to the missing `this.setState` in his answer? or something else? – 0xdeadbeef Jul 02 '23 at 09:36