【问题标题】:How to loop through/with await axios?如何循环/使用等待 axios?
【发布时间】:2019-11-07 00:29:17
【问题描述】:

我在通过 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)
        }
    }

}

【问题讨论】:

  • 如果您说${proxy}https://fantasy.premierleague.com/api/element-summary/ 有效但${proxy}https://fantasy.premierleague.com/api/element-summary/${i}/ 无效,那么这是否意味着您不应该传入i 路径?
  • 你设置了那个路由吗? element-summary/1 到 element-summary/500 是否存在?否则你会得到不存在的 404
  • 我想通了,谢谢大家

标签: javascript loops for-loop async-await axios


【解决方案1】:
  1. 您有多确定有 500 页可供查看?
  2. 重构您的 try-catch 以便您继续发送请求 任何失败的回报
  3. 当您说“如果我删除循环它可以工作”时,您的意思是 /api/element-summary/1/ 存在,但您的循环/请求可能会得到一个 索引 15 或 123 或 468 上的 404...

像这样尝试并告诉我们:

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

【讨论】:

  • 虽然这确实是一个强大的解决方案,也是一种很好的做法,但是您可以从 i=1 开始循环,因为我手动检查了链接,并且是 /0/ 导致了这个问题。
  • 我用 500 检查它们实际上是 567:D 问题是 i = 0 虽然没有 ID 0。非常感谢,它有效
  • 很高兴知道,玩得开心!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 2020-11-10
  • 2021-03-02
  • 2016-03-24
  • 2019-12-09
  • 2023-01-20
相关资源
最近更新 更多