Top tips for utilizing numerous XMLHttpRequests efficiently

I am attempting to retrieve 8 JSON objects from 8 different URLs. I have stored the query string that needs to be modified in an Array, and I am looping through it using a for loop. Below is my code:

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

var request = new XMLHttpRequest();

for (var i = 0; i < index.length; i++) {

    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];

    request.open("GET", url);
    request.onload = function() {
        var data = JSON.parse(request.responseText);
        console.log(data);
    }
    request.send();
}

At this point, my goal is to simply display each JSON object on the console. However, I am only able to display the last JSON with the last index item (noobs2ninjas).

Can anyone explain why this is happening? How can I retrieve all the JSON objects that I need?

Thank you

Answer №1

Could someone please clarify why and how can I obtain all the necessary JSON data?

If you want to send a second request after the first one has finished, you must wait for the initial request to complete. To maintain the order of responses in an array, you can loop through each array element and proceed to the next element only after receiving a response:

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var request = new XMLHttpRequest();
(function loop(i, length) {
    if (i>= length) {
        return;
    }
    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];

    request.open("GET", url);
    request.onreadystatechange = function() {
        if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            var data = JSON.parse(request.responseText);
            console.log('-->' + i + ' id: ' + data._id);
            loop(i + 1, length);
        }
    }
    request.send();
})(0, index.length);

If you prefer executing all requests asynchronously and concurrently, the request variable should be declared and scoped inside the loop, creating a separate request for each array element. You have several options like:

  • using let
  • defining a callback
  • utilizing IIFE
  • employing array .forEach() instead of a for loop

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

for (var i = 0; i < index.length; i++) {

    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];

    let request = new XMLHttpRequest();
    request.open("GET", url);
    request.onreadystatechange = function() {
        if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            var data = JSON.parse(request.responseText);
            console.log('-->' + data._id);
        }
    }
    request.send();
}

In accordance with @Wavesailor's suggestion, if you need to perform a mathematical computation at the end of the calls:

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var request = new XMLHttpRequest();
(function loop(i, length, resultArr) {
    if (i>= length) {
        console.log('Finished: ---->' + JSON.stringify(resultArr));
        return;
    }
    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];

    request.open("GET", url);
    request.onreadystatechange = function() {
        if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            var data = JSON.parse(request.responseText);
            console.log('-->' + i + ' id: ' + data._id);
            resultArr.push(data._id);
            loop(i + 1, length, resultArr);
        }
    }
    request.send();
})(0, index.length, []);

Answer №2

The issue arises when you initialize

var request = new XMLHttpRequest();

outside the for loop, resulting in only one request instance.

To rectify this, place it inside the for loop.

Keep in mind that ajax runs asynchronously, leading to results appearing in a non-sequential order.

The variable i's value should be declared with the let keyword for creating a block scope local variable.

let facilitates declaring variables limited in scope to the block.

let is commonly employed as a remedy for closures.

You can also utilize an array to store the XMLHttpRequest instances.

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
requests=new Array(index.length);
for (let i = 0; i < index.length; i++) {
    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];
    requests[i] = new XMLHttpRequest();
    requests[i].open("GET", url);
    requests[i].onload = function() {
        var data = JSON.parse(requests[i].responseText);
        console.log(data);
    }
    requests[i].send();
}

Answer №3

If you're looking for an alternative to using XMLHttpRequest, consider trying out the Fetch API combined with Promise.all().

You can fetch data from multiple channels by providing an array of channel names like ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp"]. Then simply map over the array and use fetch() with the URL to each channel's data. Finally, utilize Promise.all() to handle multiple promises and extract the JSON data from each response.
.as-console-wrapper {
max-height: 100% !important;
}

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

Adjusting the mesh position in WebGL/Three.js

Seeking some guidance on three.js. How can I apply an offset to a mesh? You can find the basic code here: I am looking to set a position offset and have that point serve as the rotation reference. I attempted: mesh.applyMatrix( new THREE.Matrix4().makeTr ...

Having trouble correctly displaying an image from a JSON within a tableView cell

I need to retrieve logos of cryptocurrencies and display them in tableView cells. The JSON data has the following structure: "data": { "1": { "id": 1, "name": "Bitcoin", ...

What is the purpose behind jade disregarding line breaks and spaces when rendering code?

Utilizing Jade, I am generating HTML by executing the code var generateCodeBlock = jade.compile('div !{text}', {pretty: true});. My aim is to create the following: <div> var json = { labelA: 'a', labelB: 2 ...

What are the steps to incorporate npm into a Wix website editor?

Has anyone successfully installed Twilio on the Wix website editor? I can't seem to locate any console or npm. Any tips on how to get it up and running? ...

Exploring a Discord.js collection: tips for accessing and manipulating objects within an array in the collection

I have a discord.js Collection that contains information about dispatcher and queue objects. Here is the structure: Collection(1) [Map] { '403547647215927306' => { dispatcher: StreamDispatcher { _writableState: [WritableState], ...

Updating a property value within a JSON object: Adjusting attributes in a JSON data format

How can I modify a specific key's value in a JSON array like the following example: input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}] ...

How can information be exchanged between PHP and JavaScript?

I am working on a concept to display a graph of someone's scores within a div element. The process involves a button that triggers the graph drawing function upon clicking. Additionally, there is a data retrieval function that retrieves information fr ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

What is the best way to prepare a DeserializationContext with custom domain objects for use in the deserialization process?

SPACE In the realm of coding, there exist two distinct entities known as ProjectSchema and PageSchema. The latter relies heavily on the former for its functionality. class ProjectSchema {} class PageSchema { public PageSchema(ProjectSchema schema) {} ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

Is it possible to incorporate an HTML5 YouTube video without using an iframe tag

Can an HTML5 version of a YouTube video be embedded without the need for an iframe? ...

The animation is disrupted by multiple clicks in jQuery

Here is a basic form example: <form id="form" action="file.php" method="POST"> <input class="form-control" type="number" name="p" value="0"> <label for="p">Text</label> <input class="form-control" type="number" name=" ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

Is there a method to retrieve news image previews from bing-api news articles?

Is it possible to retrieve thumbnails associated with news items using the Bing API? Bing.com provides images for each news item (for example, ) and one would expect this feature to be included in the API as well. ...

Clickability issue in Angular's ui-router: Non-responsive Links

I am trying to implement angular-ui-router to manage my views, but I am encountering an issue. The two links in the view below are not responsive when clicked. Even though Angular changes the variable with the link label, I am unable to interact with them. ...

What could be the reason for scope.$watch failing to function properly?

My AngularJS directive has a template with two tags - an input and an empty list. I am trying to watch the input value of the first input tag. However, the $watch() method only gets called once during initialization of the directive and any subsequent chan ...

Deactivate debugging data for Tensorflow JS

Is there a way to turn off all debugging logs in Tensorflow JS similar to what can be done in Python with setting an environment variable and calling a function? Disable Debugging in Tensorflow (Python) According to the top answer: import os os.environ[ ...

The express-unless plugin in Node.js allows you to exclude specific paths from the middleware.auth

I need help implementing express-unless to exclude a /health path from using middleware.auth. Unfortunately, I am facing syntax issues and unable to test this locally. Using localSite == true is not compatible with my environment. The error logs are shown ...

Using async/await to handle the callback function

Here is a function that saves a user in the database: exports.saveUser = ({ first_name, last_name, email, password }) => { const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *"; ...