【问题标题】:Use axios request insde a for loop在 for 循环中使用 axios 请求
【发布时间】:2020-06-07 09:10:53
【问题描述】:

我是 js 的初学者。我正在使用 vuejs、axios 和这个 api https://www.balldontlie.io 来完成一个家庭作业项目。这个项目一定要咨询nba球员的数据。我需要你的帮助来解决问题。这是我的代码:

var app = new Vue({ 
  el: '#app',
  data: {
    teams: null,
    players: [],
    selectedTeam: null,
    selectedTeamPlayers: [],
    selection: false,
    id : [],
    season_averages : []
  },
  methods: {
    getAllPlayers() {
      axios.get('https://www.balldontlie.io/api/v1/players?per_page=100').then(response => {
        let total = response.data.meta.total_pages;
        let req = [];
        let url = 'https://www.balldontlie.io/api/v1/players?per_page=100&page=';
        for (let i = 1; i <= total; i++) {
          req.push(axios.get(url + i));
        }

        axios.all(req).then(axios.spread((...responses) => {
          for (let i = 0; i < responses.length; i++) {
            let jsonPlayers = responses[i].data.data;

            for (let j = 0; j < jsonPlayers.length; j++) {
              this.players.push(jsonPlayers[j]);
              this.id.push(jsonPlayers[j].id);
            }
          }
          console.log(this.id);
        }));

      });

    },
    getSeasons() {
      let seasons = getAllplayers(); 
      let sa = [];
      for (var i = 0; i < seasons; i++) {
            axios.get("https://www.balldontlie.io/api/v1/season_averages?player_ids[]=" + i).then(response => {
            sa[i] = response.data.data;
            for (var i = 0; i < sa.length; i++) {
                this.season_averages.push(sa[i]);
            }

      });   
    }

      console.log(season_averages);
    }

  },
  mounted() {
    this.getSeasons();
    this.getAllPlayers();

  }
});

所以我请求获取 nba 球员和球队的数据。在这个脚本中,我的第一个函数返回一个仅包含玩家 id 的 json 结构。第二个应该返回所有球员的赛季平均值。但是,您只能访问特定玩家的统计数据。 我的意思是,您可以通过在 url 参数中传递的 id 访问统计玩家。

示例:https://www.balldontlie.io/api/v1/season_averages?player_ids[]=237 此网址显示 id 等于 237 的玩家的赛季平均值。

所以我想要做的是获取所有玩家,为此我必须获取所有玩家的 ID。这就是为什么我需要第一个功能。我将在第二个函数中使用它来将每个 id 与 api 的 url 连接起来。所以我可以访问它们并将它们全部存储到一个数组中并返回所有的统计信息。

我的问题是如何在 axios 请求中使用 for 循环来获取每个玩家的赛季平均值?

问候

YT

【问题讨论】:

    标签: javascript vue.js for-loop axios


    【解决方案1】:

    您可以使用async/await 处理此问题。 假设我们有一系列想要从水果篮中取出的水果。

    const fruitsToGet = ['apple', 'grape', 'pear']
    

    我们只是创建一个函数,在一段时间后返回一个特定的水果:

    const sleep = ms => {
      return new Promise(resolve => setTimeout(resolve, ms))
    }
    
    const getNumFruit = fruit => {
      return sleep(1000).then(v => fruitBasket[fruit])
    }
    

    我们将遍历这个数组。

    const forLoop = async _ => {
      console.log('Start')
    
      for (let index = 0; index < fruitsToGet.length; index++) {
        // Get num of each fruit
      }
    
      console.log('End')
    }
    

    在 for 循环中,我们将使用getNumFruit 来获取每个水果的数量。我们还会将该号码记录到控制台中。

    由于getNumFruit 返回一个承诺,我们可以在记录之前等待解析的值。

    const forLoop = async _ => {
      console.log('Start')
    
      for (let index = 0; index < fruitsToGet.length; index++) {
        const fruit = fruitsToGet[index]
        const numFruit = await getNumFruit(fruit)
        console.log(numFruit)
      }
    
      console.log('End')
    }
    
    

    当您使用 await 时,您希望 JavaScript 暂停执行,直到等待的 Promise 得到解决。这意味着 for 循环中的 await 应该按顺序执行。

    结果如你所愿

    这种行为适用于大多数循环(例如 while 和 for-of 循​​环)……

    但它不适用于需要回调的循环。需要回退的此类循环的示例包括 forEach、map、filter 和 reduce。在接下来的几节中,我们将了解 await 如何影响 forEach、map 和 filter。 Source

    【讨论】:

    • 感谢您的回答,但我真的不明白如何用我的代码实现它。能不能说的详细点?
    【解决方案2】:

    据我所知 - 您正在编写异步代码并期望同步执行。当你的作业是包含这两个函数时——那么它们都应该返回 Promises。

    如果您只想为玩家添加一些统计数据 - 也可以采用更简单的方法。

    const playerurl = 'https://www.balldontlie.io/api/v1/players?search=LeBron';
    const statsurl =
      'https://www.balldontlie.io/api/v1/season_averages?player_ids[]=';
    
    axios.get(playerurl).then(playerData => {
      const statsPromises = playerData.data.data.map(function(player) { // Use Array.map to create promises
        return axios.get(statsurl + player.id).then(function(result) {
          return new Promise(function(resolve) { // Chain promises
            player.stats = result.data.data;
            resolve(player); // Finally resolve the player and stats
          });
        });
      });
    
      Promise.all(statsPromises).then(function(playerStats) {
        console.log(JSON.stringify(playerStats));
      });
    });
    
    [
      {
        "id": 237,
        "first_name": "LeBron",
        "height_feet": 6,
        "height_inches": 8,
        "last_name": "James",
        "position": "F",
        "team": {
          "id": 14,
          "abbreviation": "LAL",
          "city": "Los Angeles",
          "conference": "West",
          "division": "Pacific",
          "full_name": "Los Angeles Lakers",
          "name": "Lakers"
        },
        "weight_pounds": 250,
        "stats": [
          {
            "games_played": 52,
            "player_id": 237,
            "season": 2019,
            "min": "34:53",
            "fgm": 9.58,
            "fga": 19.52,
            "fg3m": 2.12,
            "fg3a": 6.15,
            "ftm": 3.85,
            "fta": 5.52,
            "oreb": 0.96,
            "dreb": 6.75,
            "reb": 7.71,
            "ast": 10.73,
            "stl": 1.27,
            "blk": 0.46,
            "turnover": 3.98,
            "pf": 1.71,
            "pts": 25.12,
            "fg_pct": 0.491,
            "fg3_pct": 0.344,
            "ft_pct": 0.697
          }
        ]
      }
    ]
    

    也许还有更多工作要做 - 这就是你和家庭作业的用武之地!

    【讨论】:

    • 是的,这正是我想要的,但与所有玩家一起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    相关资源
    最近更新 更多