【问题标题】:How can i request api more faster in for loop?如何在 for 循环中更快地请求 api?
【发布时间】:2023-03-06 02:25:01
【问题描述】:

我用 riot api 开发我的玩具项目。(英雄联盟游戏) 我有一个问题。如您所见,我请求在 for 循环中使用 riot api。 需要 20 秒……这就是问题所在。我认为 riot api 不是问题。 我认为只是在 for 循环中请求是问题所在。 我怎样才能让它比现在更快?请帮帮我ㅠ.ㅠ

  for (let cnt = 0; cnt < 20; cnt++) {
    let temp = await api.getMatchInfo(res.matches[cnt].gameId);
    if (temp.gameMode === "CLASSIC" && temp.gameDuration >= 800) {
      console.log("gameList:", temp);
      temp["cnt"] = cnt;
      gameList.push(temp);
      rankCnt++;
    }
  }

【问题讨论】:

    标签: reactjs api for-loop request axios


    【解决方案1】:

    您可以通过Promise.all 使其并行,而不是对每个for 循环进行序列请求。你可以在这里看到更多https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    const promises = []
    for (let cnt = 0; cnt < 20; cnt++) {
      promises.push(api.getMatchInfo(res.matches[cnt].gameId)  
    }
    Promise.all(promises).then(games => {
      console.log(games)
    })
    //or
    const games = await Promise.all(promises)
    console.log(games)
    

    【讨论】:

    • 非常感谢!!我会试试看!! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多