简体   繁体   English

如何循环/等待axios?

[英]How to loop through/with await axios?

I have a problem looping through Ides then push the results to the array above, it throws out this Error: "Request failed with status code 404" but if I removed the loop it works correctly我在通过 Ides 循环然后将结果推送到上面的数组时遇到问题,它会抛出此错误:“请求失败,状态代码 404”但是如果我删除了循环,它可以正常工作

export default class GetPlayersPerMatch {
    constructor(numPlayers) {

        this.numPlayers = numPlayers;
        this.allPlayersMatchesArr = [];

    }
    async getResultsPerMatch() {
        try {
            const proxy = 'http://cors-anywhere.herokuapp.com/'

            for (let i = 0; i < 500; i++) {
                const resPerMatch = await axios(`${proxy}https://fantasy.premierleague.com/api/element-summary/${i}/`)
                this.playerData = resPerMatch.data
                console.log(this.playerData)
                this.allPlayersMatchesArr.push(this.playerData)
            }
            console.log(this.allPlayersMatchesArr) 

        } catch (error) {
            console.log(error)
        }
    }

}
  1. How sure are you there are 500 pages to look at?您有多确定有 500 页可供查看?
  2. Restruct your try-catch so that you keep on sending requests instead of returning on any fails重构您的 try-catch 以便您继续发送请求而不是在任何失败时返回
  3. When you say "if i remove the loop it works" you mean that /api/element-summary/1/ exists, but your loop/requests might get a 404 on index 15 or 123 or 468...当您说“如果我删除它可以工作的循环”时,您的意思是/api/element-summary/1/存在,但是您的循环/请求可能会在索引 15 或 123 或 468 上获得 404 ...

Try it like this and let us know:试试这样,让我们知道:

export default class GetPlayersPerMatch {
    constructor(numPlayers) {

        this.numPlayers = numPlayers;
        this.allPlayersMatchesArr = [];

    }
    async getResultsPerMatch() {
        const proxy = 'http://cors-anywhere.herokuapp.com/';

        for (let i = 0; i < 500; i++) {
            try {
                const resPerMatch = await axios(`${proxy}https://fantasy.premierleague.com/api/element-summary/${i}/`);
            } catch (error) {
                console.log(error);
            }
        this.playerData = resPerMatch.data;
        console.log(this.playerData);
        this.allPlayersMatchesArr.push(this.playerData);
        }
        console.log(this.allPlayersMatchesArr);        
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM