7

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?

3
  • You can await Promise.all(). See this question Commented May 15, 2019 at 15:45
  • some answers from here provide solutions without Promise.all: stackoverflow.com/questions/35612428/… Commented May 15, 2019 at 15:46
  • you can simply await Promise.all() Commented May 15, 2019 at 15:46

1 Answer 1

13

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

A good idea, however when you are doing it the componentDidMount.... async componentDidMount() { someFunction() } you do not get data in the response
Are you referring to the fact that i didn't have a return statement in my example?
@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?

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.