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

javascript - Axios promise in a loop - Stack Overflow

programmeradmin1浏览0评论

In React, I want to pass a function getRepos() to ponentDidMount(). getRepos() waits for another function which passes data from API call. I want to be able to put all promises in one array and then resolve it. How do I do that? Here's what I've got so far:

async getRepos() {
    const tmpRepos = [];
    const numPages = await this.getOrgPages();
    for (let page = 1; page <= numPages; page += 1) {
      axios.get(`=${page}&per_page=100&${API_KEY}`)
    }
    axios.all(tmpRepos).then(res => console.log(res));
}

In React, I want to pass a function getRepos() to ponentDidMount(). getRepos() waits for another function which passes data from API call. I want to be able to put all promises in one array and then resolve it. How do I do that? Here's what I've got so far:

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

But just logs an empty array

Share Improve this question asked Sep 24, 2017 at 15:11 user7605119user7605119 5
  • You'd done everything except push to tmpRpos. – T.J. Crowder Commented Sep 24, 2017 at 15:17
  • Side note: What if the number of pages changes while you're doing this? Perhaps better to just query starting from 1 until you get an error? – T.J. Crowder Commented Sep 24, 2017 at 15:18
  • I get the number of pages in response to the API call in getOrgPages() function – user7605119 Commented Sep 24, 2017 at 15:20
  • Hence the "...while you're doing this..." part of the ment. Think race condition. – T.J. Crowder Commented Sep 24, 2017 at 15:32
  • 2 Good question. I will need to think about it – user7605119 Commented Sep 24, 2017 at 17:02
Add a ment  | 

1 Answer 1

Reset to default 5

Create a new array, and fill it by results of axios.get calls, use this array in 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./orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`);
      ops.push(op);
    }

    let res = await axios.all(ops);
    console.log(res);
}
发布评论

评论列表(0)

  1. 暂无评论