The performance of my JavaScript function seems to be lagging

I'm currently gathering extensive data from an API using an async function that iterates through a large amount of information using a loop. I'm sending about 100 requests and it's taking approximately 8 seconds to complete.

Are there any techniques or methods that I could implement to optimize the speed of my script?

async function getPlayerData() {
  // Retrieve current room information
  const response = await fetch(url);
  let teams = await response.json();
  let players = teams.players;
  let playerArray = players.length;
  for (var i = 0; i < playerArray; i++) {
    let username = players[i].username;
    let userId = players[i].id;
    // Retrieve user matches
    const userMatch = await fetch(`https://api.site.com/user_profile/get_latest_matches?_=&id=${userId}&page=1`);
    let matchList = await userMatch.json();
    let matchListArray = matchList.length;
    for (var ii = 0; ii < matchListArray; ii++) {
      // Retrieve match statistics
      const matchListResponse = await fetch(`https://api.site.com/match/get?_=&id=${matchList[ii].id}`);
      let matchListResponseStats = await matchListResponse.json();
      
      async function matchData() {
        if (matchListResponseStats.players === null) {
          const kills = 0;
          const deaths = 0;
          const headshot = 0;
          const headshotProc = 0;
          return [kills, deaths, headshotProc, headshot];
        } else {
          const filterArray = matchListResponseStats.players[i];
          console.log(filterArray);
          console.log(filterArray.kills);
          console.log(filterArray.deaths);
          console.log(filterArray.headshots);
        }
      }
      matchData();
    }
  }
}
getPlayerData();

Answer №1

To optimize performance, consider using Promise.all with .map instead of for loops with await inside. This approach allows requests to run in parallel, initiating each task as soon as possible without waiting for others to finish:

async function getplayerdata1() {
  // Get current room
  const response = await fetch(url);
  const { players } = await response.json();
  return Promise.all(players.map(async (player, playerIndex) => {
    const { username, id } = player;
    // read user matches
    const response = await fetch(`https://api.site.com/user_profile/get_latest_matches?_=&id=${id}&page=1`);
    const matchlist = await response.json();
    return Promise.all(matchlist.map(async ({ id }) => {
      // Read match stats
      const matchlistResponse = await fetch(`https://api.site.com/match/get?_=&id=${id}`);
      const matchlistResponsestats = await matchlistResponse.json();
      // get 1st match stats
      if (matchlistResponsestats.players === null) {
        return [0, 0, 0, 0];
      } else {
        const filterArray = matchlistResponsestats.players[playerIndex];
        console.log(filterArray)
        console.log(filterArray.kills)
        console.log(filterArray.deaths)
        console.log(filterArray.headshots)
      }
    }));
  }));
}

By sending out all possible requests simultaneously, you can maximize efficiency. However, if the API or your connection cannot handle the load, you may need to implement request throttling.

Keep in mind that most browsers limit concurrent requests to around 6. Therefore, if you initiate a batch of 100 requests, only approximately 6 may be active at a time. Nevertheless, if the underlying protocol is http2, requests can be multiplexed and transmitted together in a single action.

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

Enabling Cross-Origin Resource Sharing in Node.js 14

I'm diving into the world of JavaScript and Node.js as I work on creating a new REST-based API using NodeJS. However, I've hit a roadblock when trying to fetch data from the API due to a CORS issue. Browser console error message: Access to fetch ...

Functional Components with Methods in ReactJS

When creating a functional stateless component that requires methods to access props, is there a recommended approach or best practice to follow? For instance: function Stateless(props) { function doSomething(props) { console.log(props); } ...

Tips for handling TypeError when testing formgroups in Angular unit tests---How to address TypeError

While attempting to conduct unit testing on my form fields in Angular, I encountered an issue with Karma stating that my property is undefined. When I logged the formGroup, it returned as undefined. However, upon logging my component, all parameters were r ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Fetching data from database and populating dropdown menu through Struts 2 action class with the assistance of jtable

Utilizing the jtable jQuery plugin (http://jtable.org/) in my current project has been a game-changer. It allows for the creation of AJAX based CRUD tables without the need to code HTML or JavaScript. For more details, refer to this image: The jtable cod ...

Leveraging the power of JavaScript and possibly regular expressions to extract numerical values from a

I am attempting to extract a variable number from the text provided in the following example: Buy 5 for € 16.00 each and save 11% Buy 50 for € 15.00 each and save 17% Buy 120 for € 13.00 each and save 28% Buy 1000 for € 10.00 each and save 45% Th ...

Issues encountered - nodejs-lts (exit code 1603) - Problem occurred during execution of 'C:ProgramDatachocolateylib odejs-lts oolschocolateyinstall.ps1' script

Encountering Issues with Installing 64-bit Version of nodejs-lts... Received a Generic MSI Error during installation, indicating a local environment issue rather than a problem with the package or MSI file itself. Possible reasons for thi ...

Apply a new class to all Radio buttons that were previously selected, as well as the currently

Struggling with a simple code here, trying to figure out how to add color (class) to the selected radio button and the previous ones. For example, if button No3 is selected, buttons 1, 2, and 3 should get a new color. Below is the basic code snippet: < ...

Using Javascript and jQuery to modify the element's ID

I've been trying to automate the loading process of articles on my website, but I'm having trouble with the line $(tytul).html(data);. Is there a way to get this working correctly? var numboart = 3; $(document).ready(function(){ for(i=0;i& ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

The integration of single page applications and <form> elements is a powerful combination in web development

Is there still value in using a <form> element over a <div> element when developing single page applications? I understand the purpose of the <form> element for traditional form submissions with a full page reload, but in the context of ...

Having trouble with jQuery's 'OR' not functioning properly when iterating through mandatory input elements

In the process of creating a fallback for required HTML5 attributes for different input types, I encountered an issue with checking the ':checked' status of radio buttons and using the 'OR' || operator within the loop: if (self.val() = ...

The unusual behavior of setTimeout in loopback 3

I'm puzzled by the peculiar behavior exhibited by loopback. To illustrate, I have created a straightforward remote method shown below. Device.getTypes = function(next) { let result = {0: {val: 10}}; setTimeout(function() { result[0].w ...

Enhance the visual appeal of Autodesk Forge Viewer by incorporating environmental textures

Is there a way to incorporate an environmental texture into Autodesk Forge Viewer v6.0? I know in Three.js you can apply a texture to the scene's background and environment, so how would I achieve this in APS viewer? I'm not looking for a skybox ...

Always ensure that an element remains at the bottom during the sorting process

Currently, I have a list of items with an integer attribute that aids in sorting the list. However, I am looking for a way to designate specific items to always appear at the bottom of the list regardless of the sorting criteria. Is there a singular valu ...

What is preventing python from eliminating these numbers from my array?

My goal is to eliminate all numbers within the range of 0 to 1000 that have fewer than two digits. This is my approach: numbers = range(0,1001) #validate for two or more digits for number in numbers: if len(str(number)) < 2: numbers.remove( ...

The date of posting will always be '0000-00-00 00:00:00'

I'm experiencing an issue with my JavaScript code for writing reviews. Previously, it worked fine, but now the 'datePosted' column consistently outputs the default '0000-00-00 00:00:00'. writeReview(request, respond) { va ...

Creating interactive checkboxes dynamically using form data - a step-by-step guide

Scenario When a user fills out an order form, they have the option to choose a bike type and select from the corresponding options available for that bike type. Current Issue I am facing a situation where I need to include a checkbox with all possible op ...

Link embedded in prism formatting, encased in code snippet

In the HTML template, I have the following code snippet: <pre> <code class="language-markup"> {% filter force_escape %} <Item> <MarkUp><a href="http://google.com">Google</a></MarkUp> <No ...

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...