【问题标题】:Axios promise in a loop循环中的 axios 承诺
【发布时间】:2018-03-05 14:48:28
【问题描述】:

在 React 中,我想将函数 getRepos() 传递给 componentDidMount()getRepos() 等待另一个从 API 调用传递数据的函数。我希望能够将所有承诺放在一个数组中,然后解决它。我怎么做?到目前为止,这是我所得到的:

async getRepos() {
    const tmpRepos = [];
    const numPages = await this.getOrgPages();
    for (let page = 1; page <= numPages; page += 1) {
      axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`)
    }
    axios.all(tmpRepos).then(res => console.log(res));
}

但只记录一个空数组

【问题讨论】:

  • 除了推送到tmpRpos之外,您已经完成了所有工作。
  • 旁注:如果在您执行此操作时页数发生变化怎么办?最好从 1 开始查询直到出现错误?
  • 我在getOrgPages()函数中得到响应API调用的页数
  • 因此 "...while you're doing this..." 部分的评论。想想比赛条件。
  • 好问题。我需要考虑一下

标签: javascript reactjs promise async-await axios


【解决方案1】:

创建一个新数组,并用axios.get 调用的结果填充它,在axios.all 中使用这个数组:

async getRepos() {
    const ops = [];
    const numPages = await this.getOrgPages();
    for (let page = 1; page <= numPages; page += 1) {
      let op = axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`);
      ops.push(op);
    }

    let res = await axios.all(ops);
    console.log(res);
}

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2018-03-25
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2016-10-11
    相关资源
    最近更新 更多