Ensure that you do not display the result until all Ajax calls have finished processing

When faced with a challenging problem, I persist through multiple attempts and seek your assistance in finding a solution.

My current goal is to populate a table with the number of viewers for a specific streamer using the Twitch API.

To achieve this, I carefully construct my ajax call:

viewerCount(streamer){
    let viewers = [];
    let streamerList = streamer;

    for (let i = streamer.length-1; i >= 0; i--){
    
        $.ajax({
            type: 'GET',
            url: 'https://api.twitch.tv/helix/streams?user_login='+streamerList[i]+'',     
            dataType:'JSON',
            headers: {
                "Client-ID": 'bgbezb2vov7jc4twxauhw3yh30ubbx',
                "Authorization": "Bearer "+this.auth
            },                   

            success: function(data) {
                viewers.push([i, streamerList[i], data['data'][0]['viewer_count']])
            },

            error: function(data){
                console.log(data)
            }            
        })
    };

}

Once I have gathered the results, I populate my table. However, I encounter an issue where I wish to wait for all ajax calls to complete before displaying the information. I attempted to use promise.all without success.

I appreciate any help you can provide on this matter.

Answer №1

To determine if all calls have been completed, you can utilize the following condition (refer to the code comments for more details):

    viewerCount(streamer){
    let viewers = [];
    let streamerList = streamer;
    let completedCalls = 0; // initialize a new variable
    for (let i = streamer.length-1 ; i >=0 ; i--){               
    
    $.ajax({
            type: 'GET',
            url: 'https://api.twitch.tv/helix/streams?user_login='+streamerList[i]+'',     
            dataType:'JSON',
            headers: {
                    "Client-ID": 'bgbezb2vov7jc4twxauhw3yh30ubbx',
                    "Authorization": "Bearer "+this.auth
                    },                   
            success: function(data) {
                viewers.push([i, streamerList[i], data['data'][0]['viewer_count']]);
            completedCalls++; // increment completedCalls
            },
            complete: function() { 
              if(completedCalls === streamer.length) {
                   displayYourResult();
              }
           },
            error: function(data){
                console.log(data)
            }            
        })
    };

}

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

Struggling to detect mistakes utilizing the createUserWithEmailAndPassword() function in Firebase

My attempts to debug the issue have been unsuccessful, resulting in my code not identifying errors like creating a user with an email that is already registered. While it does provide a response, it's not the one I anticipated such as firebase/email-i ...

What is the best way to compare and identify the variances between two JSON documents in Marklogic using JavaScript?

Is there a way to analyze and compare two JSON documents in Marklogic using JavaScript to identify any differences between them? ...

Enhancing Redux efficiency with substantial data structures

I have developed a web application using Redux and React. It is an analytics application that displays a significant amount of data. However, I am facing performance issues as the size of my data store increases. What is the best approach to prevent perfo ...

Retrieving data from a nested array within an array of objects using JavaScript

Below is an example of an array object: const data = [ { name: "A", values: [ { name: "PASS", value: 36, }, ], }, { name: "B", values: [ { ...

Using a local variable with jquery getJSON: A comprehensive guide

I am looking to expand the autocomplete capabilities of Ace Editor and I require a JSON file containing words. Here is my code snippet: function load_completions() { var object = $('#preview').attr('class'); $.ajax({ ...

Using Npm to install a module results in an abundance of files being provided

Back when I used npm install 6 months ago to install a module, it would create a new folder under node_modules containing all the files for that module. However, now when I use it, it creates multiple files for one module. How can I install a module to a ...

Combine javascript and css sequentially

I have a few tasks that involve combining CSS and JavaScript together. Here is an example of how I accomplish this: gulp.task('javascript', function() { return gulp.src([ libPath + 'jquery-2.1.4.min.js', libPath + '*.js& ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

Double Ajax calls being made in Laravel application

I am working on a Laravel application for managing tasks. The application has a form with four fields: one for the CSRF token, two hidden fields for IDs, and an input field to capture the task title. For submitting the form, I have implemented AJAX. Howev ...

Is it feasible to utilize the .fadeTo() function in jQuery multiple times?

I need some help with writing a script that will display a warning message in a div tag every time a specific button is pressed. I chose to use the fadeTo method because my div tag is within a table and I want to avoid it collapsing. However, I'm noti ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

How can I monitor and handle JavaScript errors without causing TestCafe tests to fail?

As I begin writing TestCafe tests, a problem arose on our website - a JS error in the console causing test failures. While it was satisfying to catch this issue, it also highlighted the fact that even minor JS errors could lead to test failures and hinder ...

The attempt to log in using AJAX and PHP was unsuccessful

Why does the output always show a false alert even though the email and password match those in the database? PHP: <?php include 'db.php'; $email = trim($_POST['email']); $password = trim($_POST['password'] ...

What is the best way to modify the Xtype attribute based on whether the device is running on Android or iOS

I am currently working on a project using Extjs6.0.2, but I have encountered an issue with creating the xtype: 'namefield'. It seems that this type of xtype is supported on Android devices but not on iOS devices. Despite this challenge, I am dete ...

Troubleshooting Problem: Incompatibility with Angular 1 and Angular 2 Hybrid Application causing Display Issue with Components

In my development work, I have created a unique hybrid application that combines Angular 1 and Angular 2 functionalities. This hybrid setup was achieved by following the guidelines provided in two helpful resources: Upgrading from AngularJS and Migrating A ...

"Implementing a .gif Preloader Before Executing Animation with jQuery

I am currently working on an animation project using Jquery. The project consists of various images in .png format and div tags, with some being small file sizes while others are as large as 5mb. Is there a way to incorporate a pre-loading (.gif) animatio ...

JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overl ...

Eliminate any unnecessary zeros at the end of a number within AngularJS interpolation

Although there are solutions available for plain JavaScript code, unfortunately they are not applicable in this particular scenario. I have a table that needs to be populated with data. The current code snippet is as follows: <tr ng-repeat="rows in $ ...

Is it possible to alter CSS based on the width of the webpage using javascript

We are currently developing a web application that will be deployed on various devices such as mobile phones, iPads, iPhones, and Android. Instead of using user agents to show different views, I prefer having CSS that adjusts based on the screen width. We ...