Steps for populating an array with data from multiple asynchronous requests

Trying to retrieve names and scores from two arrays, player_name and player_mmr. However, using player_name[i] and player_mmr[i] in the fillplayer function is returning undefined. It feels like I'm overlooking something simple here, but I just can't seem to figure it out. My guess is that it has something to do with how push is being used.

var btnmatch = document.querySelector('#get-data');
var btnchat = document.querySelector('#get-chat');
var matchid = document.querySelector('#match-id');
var tableheaders = [
    'Hero',
    'level',
    'Name',
    'Kills',
    'Deaths',
    'assists',
    'GPM',
    'XPM',
    'HD',
    'TD'
];

var dataheaders = [
    "hero_id",
    'level',
    'personaname',
    'kills',
    'deaths',
    'assists',
    'gold_per_min',
    'xp_per_min',
    'hero_damage',
    'tower_damage'
];

var playerids = [
    'player1',
    'player2',
    'player3',
    'player4',
    'player5',
    'player6',
    'player7',
    'player8',
    'player9',
    'player10'
];

var playeraccounts = [];
var requests = [];
var playersdata = [];
var player_name = [];
var player_mmr = [];

btnmatch.addEventListener('click', function () {
    GetMatchData(matchid.value);

});

btnchat.addEventListener('click', function () {
    for (i in playeraccounts) {
        requests[i] = new GetPlayerData(playeraccounts[i]);
    }
    console.log(player_name);
    console.log(typeof player_name);
    console.log(player_mmr);
    fillplayer();

});


function GetPlayerData(accountid) {
    var Url = 'https://api.opendota.com/api/players/' + accountid;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", Url, true);
    xmlHttp.onreadystatechange = function ProcessRequestPlayer() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            if (xmlHttp.responseText == "Not found") {
                console.log("not found");
            } else {
                var info = xmlHttp.responseText;
                var playerjson = JSON.parse(info);

                player_name.push(playerjson.profile.personaname);
                if (playerjson.solo_competitive_rank === null) {
                    player_mmr.push(playerjson.mmr_estimate.estimate);
                } else {
                    player_mmr.push(playerjson.solo_competitive_rank);
                }
            }
        }
    };
    xmlHttp.send();
}

function GetMatchData(id) {
    var Url = 'https://api.opendota.com/api/matches/' + id;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", Url, true);
    xmlHttp.onreadystatechange = function ProcessRequestMatch() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            if (xmlHttp.responseText == "Not found") {
                console.log("not found")
            } else {
                var info = xmlHttp.responseText;
                var testjson = JSON.parse(info);

                createTable2(testjson);
                getaccountids(testjson);

            }
        }
    };
    xmlHttp.send();
}

function getaccountids(json) {
    Object.keys(json.players).forEach(function (i) {
        playeraccounts.push(json.players[i].account_id);
    });
}

function fillplayer() {
    console.log(player_name);
    console.log(player_mmr);
    for (var i = 0; i < playerids.length; i++) {
        console.log(player_name[i]);

        document.getElementById(playerids[i]).getElementsByClassName('name')[0].innerHTML = player_name + ': ';
        document.getElementById(playerids[i]).getElementsByClassName('mmr')[0].innerHTML = player_mmr[i];
    }
}

function createTable2(json) {
    // Create table.

    var table = "<table class='game-table'>";
    table += "<thead>";
    table += "<tr>";
    for (var i = 0; i < 10; i++) {
        table += "<th>" + tableheaders[i] + "</th>";

    }
    table += "</tr>";
    table += "</thead>";
    table += "<tbody>";

    for (var i = 0; i < 5; i++) {
        table += "<tr class='radiant'>";
        for (var x = 0; x < dataheaders.length; x++) {
            table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
        }
        table += "</tr>";
    }

    for (var i = 5; i < 10; i++) {
        table += "<tr class='dire'>";
        for (var x = 0; x < dataheaders.length; x++) {
            table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
        }
        table += "</tr>";
    }
    table += "</tbody>";
    table += "</table>";
    var sectie = document.getElementById('table');
    if (json.radiant_win == false) {
        var winnertekst = document.createTextNode('Dire Victory');
    } else {
        var winnertekst = document.createTextNode('Radiant Victory');
    }

    console.log(table);
    console.log(typeof table);
    console.log(sectie);
    document.getElementsByClassName('winnersect')[0].appendChild(winnertekst);
    sectie.innerHTML = table;
}

Answer №1

As marekful suggested, you have the option to utilize promises or explore Async Functions. Additionally, if IE compatibility is not a concern for you, consider implementing the Fetch API in place of XMLHttpRequest for a more streamlined structure. Both of these options yield promises that can be easily consumed. For further guidance on combining fetch with async functions, check out this resource: JavaScript Fetch API and using Async/Await .

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

Error: The function referenced is not defined when the page loads

Trying to incorporate two different script tags in a single HTML page has been quite a task for me. The first script tag contains the location of a JS file that I need to use for a specific function, while the second script tag is where I have written anot ...

React's shorthand conditional rendering displaying incorrect information

Do you think React cannot handle multiple conditions with its shorthand conditional syntax? I've been struggling with a particular issue that doesn't seem to make sense. The problem lies in a conditional statement where I only want to display dat ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

Having trouble retrieving a specific value from a json object

Below is the JSON data that I am dealing with: var data = {200x200: "url1", 400x400: "url2", 800x800: "url3"}; After stringifying the object and attempting to access "200x200," I encountered an issue: undefined data = JSON.stringify(data); //data = ...

Explaining the structure of a nested object within a TypeScript declaration file

As I work on my project, I encounter the challenge of importing an object created by a dynamic function. The dynamic nature of the keys on this object poses a problem for the IDE, as it cannot determine what keys are present based on the provided config. T ...

Executing an operation on every element in a Python array without utilizing the "def" keyword

Given an input array x with dimensions (1 x 3) and an output array of size 3 x 3, where each element in the output array is either the square of the value or the sum of two values from the input array. The formula to calculate non-diagonal elements is x(ro ...

Patience is key as we wait for the webpage to finish loading

I've been searching for a solution to this issue for quite some time without any success... On my webpage, I have a square texture as the background which is set to repeat in order to fill the entire page. However, when a user first enters my site, t ...

Is there a way to effectively alter an object that has been assigned in a separate file?

Seeking Assistance: I am facing an issue in my current project where I need to store a javascript object in an external file and then export it using module.exports. The challenge now is that I want another file to be able to modify a specific value withi ...

Having issues with Tailwind colors not dynamically updating in brackets

Recently, I encountered an issue where my custom colors were not working when implemented dynamically. Below, you'll find two sets of codes and screenshots: one with the dynamic code and output, and another with the static code and output. I prefer n ...

Creating a TextGeometry in THREE JS that Reacts to Mouse Movements

I have created a unique source code where the text rotates based on mouse position. // Setting up the scene const scene = new THREE.Scene(); let camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ) ...

What is the best method to choose the following sentence once the final * has been identified

In the navigation text, my objective is to pick out the final sentence following * For example; Home*Development*Mobil and Web Development I am only interested in selecting the last sentence after * --> (Mobil and Web Development) ...

Utilizing and saving JSON data in JavaScript

I am currently working on developing a 2D, top-down RPG game inspired by Zelda for the web... My plan is to organize dialog in JSON format... Right now, I have the JSON data stored in an external JavaScript file called js/json.js: function getJson() { ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Using the same geometric shapes repeatedly leads to occasional texture errors in THREE.JS

As I embark on my journey to create my first card game using THREE.js for Firefox and Chrome, I have encountered a perplexing issue with disappearing textures. The purpose of this post is to gain insights into why this issue occurs and how I can resolve i ...

Issues with jQuery Sliders

Hello there! I am currently in the process of creating a basic jQuery slideshow. The specific requirement for this slideshow is quite simple - I want the images to continuously slide to the left. I have come across numerous tutorials online, but most of th ...

Tips for improving modularity in my frontend JavaScript code?

I'm currently developing a unique Node.js / Express application that visually represents text notes as a network to offer users a clear summary of the connections between different notes. The project heavily relies on frontend functionalities, requir ...

Exploring the usefulness of `bind(this)` within a ReactJS constructor

I have a good understanding of the Javascript function bind. However, I'm puzzled by why in the React.js snippet below, this is being bound again to itself. Is this related to the constructor, as this in the constructor can vary depending on how it&ap ...

Obtain the inner HTML of a component and store it as a variable in Vue.js 2

Imagine I have a vuejs component named child-component that is inserted into a parent component in the following manner. <child-component> <div>Hello</div> </child-component> Please note, this does not represent the template of ...

Surprising issues arise when converting a string to a datetime using Moment.js within Node.js

I am looking to convert the string '03/08/2017 01:00:01 ' into a datetime object in node.js in order to extract the specific day and month from the date. For example, for the given date, the month is 08 and the day is 03. Take a look at the foll ...

What is the issue with the Lambda code below that is causing a module error to occur?

To establish a connection with Amazon AWS, I have utilized the following code snippet that utilizes Amazon Lambda: import boto3 import json import requests from requests_aws4auth import AWS4Auth region = 'us-east-1' service = &apos ...