Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios promise in a loop

In React, I want to pass a function getRepos() to componentDidMount(). 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.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`)
    }
    axios.all(tmpRepos).then(res => console.log(res));
}

But just logs an empty array


1 Answers

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.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`);
      ops.push(op);
    }

    let res = await axios.all(ops);
    console.log(res);
}
like image 67
alexmac Avatar answered Jun 14 '26 04:06

alexmac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!