【问题标题】:fetch data from multiple apis with async await使用异步等待从多个 API 获取数据
【发布时间】:2019-10-02 19:46:25
【问题描述】:

Async/await 在异步获取数据时派上了用场,尤其是在

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 })
    }

}

此外,当从多个端点获取时,可以轻松使用

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

但是,如何使用 aync/await 而不是 Promise.all 从多个来源获取数据?

【问题讨论】:

标签: javascript reactjs async-await


【解决方案1】:

如果您想并行执行它们,那么您仍然需要 Promise.all。只是你会await 结果而不是调用.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);
  }
}

【讨论】:

  • 一个好主意,但是当你这样做时 componentDidMount.... async componentDidMount() { someFunction() } 你不会在响应中获得数据
  • 您是指我的示例中没有返回语句这一事实吗?
猜你喜欢
  • 2021-07-07
  • 1970-01-01
  • 2019-07-29
  • 2022-07-06
  • 1970-01-01
  • 2020-10-03
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多