[Vuejs]-Use axios request insde a for loop

0👍

You can use async/await for this issue.
Let’s say we have an array of fruits we want to get from the fruit basket.

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

We simply create a function that returns a specific fruit after some time:

const sleep = ms => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

const getNumFruit = fruit => {
  return sleep(1000).then(v => fruitBasket[fruit])
}

We are going to loop through this array.

const forLoop = async _ => {
  console.log('Start')

  for (let index = 0; index < fruitsToGet.length; index++) {
    // Get num of each fruit
  }

  console.log('End')
}

In the for-loop, we will use getNumFruit to get the number of each fruit. We’ll also log the number into the console.

Since getNumFruit returns a promise, we can await the resolved value before logging it.

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

When you use await, you expect JavaScript to pause execution until the awaited promise gets resolved. This means awaits in a for-loop should get executed in series.

The result is what you’d expect

This behaviour works with most loops (like while and for-of loops)…

But it won’t work with loops that require a callback. Examples of such loops that require a fallback include forEach, map, filter, and reduce. We’ll look at how await affects forEach, map, and filter in the next few sections.
Source

0👍

As far as I can see – you are writing asynchronous code and expecting synchronous execution. When you homework is to include these two functions – then they both should return Promises.

If you just want to stick some stats to a player – a simpler approach could work, too.

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
      }
    ]
  }
]

Maybe there is more to be done – that’s where you and homework come in!

Leave a comment