如何在for循环中更快地请求api?

时间:2020-04-28 08:34:01

标签: reactjs api for-loop request axios

我使用riot api开发玩具项目(英雄联盟游戏) 我有一个问题。如您所见,我请求在for循环中骚扰api。 需要20秒...这是问题所在。我认为防暴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++;
    }
  }

1 个答案:

答案 0 :(得分:0)

您可以使用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)