Leverage the Axios package to make requests within a for loop

I'm new to JavaScript and currently working on a project using Vue.js, Axios, and the API available at . The goal of this project is to retrieve NBA player statistics for a homework assignment. I could use some assistance in addressing certain issues. Below is the code I have:

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

  }
});

In this script, I am requesting NBA player and team data. The first function returns a JSON structure only containing player IDs. The second function aims to return season averages for all players. However, it can only access stats for specific players based on their ID provided as a parameter in the URL.

For example: This URL shows the season averages of the player with an ID of 237.

My objective is to gather data for all players, which requires obtaining all their IDs. That's why I need the first function - to utilize it in the second function to concatenate each ID with the API URL. This way, I can store and access all player stats efficiently.

My query is how to implement a for loop on Axios requests to fetch season averages for each player?

Thank you,

YT

Answer №1

To tackle this issue, utilizing the async/await feature is the way to go. Imagine we have an assortment of fruits that we wish to retrieve from a fruit basket:

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

We construct a simple function that delivers a particular fruit after a specified duration:

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

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

The plan is to iterate 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')
}

Within the for-loop, we will utilize getNumFruit to ascertain the quantity of each fruit. Subsequently, we will log this information into the console.

Since getNumFruit yields a promise, we await its resolved value prior to 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 employing await, it signifies that JavaScript will halt execution until the awaited promise concludes. This implies that awaits in a for-loop should be handled sequentially.

The outcome aligns with expectations

This functionality extends to most types of loops (such as while and for-of loops)…

However, it doesn't apply to loops necessitating a callback. Examples of such loops include forEach, map, filter, and reduce. The impact of await on forEach, map, and filter will be explored in subsequent sections. Source

Answer №2

It seems like there is a mix-up between asynchronous and synchronous code execution in your current setup. To properly handle the inclusion of these two functions, they should both return Promises.

If you simply need to assign statistics to a player, a more straightforward approach could also be effective.

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) { // Using Array.map to create promises
    return axios.get(statsurl + player.id).then(function(result) {
      return new Promise(function(resolve) { // Chaining promises
        player.stats = result.data.data;
        resolve(player); // Resolving the player and stats at the end
      });
    });
  });

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

Perhaps there are further enhancements to be made - that's where your effort and dedication to homework will shine!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to obtain the id of an HTML element that is generated within jQuery code?

Typically, data is retrieved in HTML by storing the html in the html file. In my case, however, I create the html element inside jQuery. So, how do I call out the div id? How can I replace document.getElementByID ("edit").innerHTML=.... when the element i ...

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

I encountered a "TypeError: Unable to access property 'name' of undefined" error when attempting to export a redux reducer

UPDATE: I encountered an issue where the namePlaceholder constant was returning undefined even though I was dispatching actions correctly. When attempting to export my selector function, I received an error: https://i.sstatic.net/MwfUP.png Here is the c ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Tips for adding styling to HTML in Vue by entering CSS code into the CodeMirror editor

Is there a way to style HTML by entering CSS code into the Codemirror editor? For instance, if we have the HTML code <head> </head>, how can I apply the CSS code, head{ color : red }, typed in the Codemirror editor to stylize this HTML code? mo ...

Sustain unbroken websocket connection with Discord using Node.js

I've been working on developing a Discord bot using the raw API, but I've encountered an issue where the bot stops functioning after some time. I suspect that this is due to neglecting to maintain the websocket connection. How can I ensure that ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

Steps for transforming an array of file names into JSON format and including a specific key

I am in the process of creating a new website that will display all the files contained in a specific folder. However, I am facing an issue with converting an array of document names into JSON format. In order to achieve this, I understand that I need to ...

Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows: Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only ret ...

The HTML file contains the complete version number of Firefox

If you're an expert in HTML, take a look at my expandable start page. I know there's room for improvement, and I'm seeking advice on automatically updating the Firefox browser version number in line 106 of the code snippet below. (Linux Mint ...

Which frameworks are categorised under Express-based frameworks?

Considering a job opportunity to develop a web app, one of the requirements is to "use node.js with an express based framework." My understanding is to use node.js with express.js, but what exactly does an express based framework entail? Does it refer to ...

Guide on implementing a Pug for loop using AJAX

For my school project, I am developing a web application similar to Tinder using Node.js, Express, and Pug. The main goal of the project is to provide potential matches to users based on either their proximity or common interests with the current user. Whe ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

Ignore linting errors in the Webpack React Fast Refresh plugin for faster performance

I have integrated the following plugin for Hot Module Replacement (HMR): https://www.npmjs.com/package/@pmmmwh/react-refresh-webpack-plugin. How do I prevent it from blocking the page display due to non-breaking errors, such as linting issues? Here is a ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

Tips for optimizing Slider Code to showcase an expanded selection of slides

I am currently troubleshooting a slider code on my ASP.NET website. After examining the HTML, JS, and CSS from the page theme, I noticed that only two slides are being displayed. However, when attempting to add a new slider HTML and adjusting the CSS for t ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...