最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fetch data from multiple apis with async await - Stack Overflow

programmeradmin2浏览0评论

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

async ponentDidMount() {
    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?

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

async ponentDidMount() {
    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?

Share Improve this question asked May 15, 2019 at 15:43 Erick MwazongaErick Mwazonga 1,3001 gold badge14 silver badges27 bronze badges 3
  • You can await Promise.all(). See this question – Chris B. Commented May 15, 2019 at 15:45
  • some answers from here provide solutions without Promise.all: stackoverflow./questions/35612428/… – Andrey Commented May 15, 2019 at 15:46
  • you can simply await Promise.all() – GifCo Commented May 15, 2019 at 15:46
Add a ment  | 

1 Answer 1

Reset to default 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);
  }
}
发布评论

评论列表(0)

  1. 暂无评论