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

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

Guide on how to navigate to the bottom of a div element using Selenium Webdriver

My current project involves a unique challenge where there is a specific div element on the webpage that acts as a popup dialog when a link is clicked (similar to Facebook reaction dialog boxes). To automate tests for this scenario, I am using Selenium We ...

Setting a false condition on jQuery's .on('canplaythrough') event

Struggling to implement a custom audio control with jQuery, but encountering some issues. I'm in the process of converting native JavaScript to jQuery for consistency in my code, however, I can't seem to get it working. The original code that is ...

Discover the method to activate the back button feature on ajax pages

I am currently working on a website that is navigated in the following way: $(document).ready(function () { if (!$('#ajax').length) { // Checking if index.html has been loaded. If not, navigate to index.html and load the hash part with ajax. ...

What is causing the list-sorter to malfunction?

This website crashes when executed: <head> <script> var numbersList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]; var orderedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...

Utilize the power of Bootstrap Modals to enhance your form validation with a seamless integration of Jquery

I have a few questions about JQuery syntax: 1) The modal is not showing up. Could this be related to an operator (&&) issue? How can I fix it? It should only appear if the input is valid. 2) How do I combine preventDefault with valid classes when submitt ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Issue: SyntaxError - JSON Parsing Error: Unexpected character '<' found in JSON data

After completing the AJAX request, I understand why I am receiving this message. The controller action method is designed to redirect to another view if everything goes smoothly. In the case of an error, it should return JSON with an error message. As I g ...

Vertical alignment in material-ui's Grid component is not functioning as expected

I have been working on this code snippet to center a button both vertically and horizontally. However, it seems like the button is not positioned correctly along the vertical axis. Any advice or guidance would be greatly appreciated! Could someone assist ...

Regular expressions are compatible with JavaScript, but unfortunately, they are not supported

After successfully implementing this regex in my JavaScript for webpage validation, I attempted to incorporate it into my PHP script as a backup. However, every string I passed through the regex failed, even correct names. In an effort to resolve the issu ...

Triggering click events in jQuery/AJAX to replace previous appends

Having some issues with page refreshes after jquery click events. This content is loaded dynamically via ajax, so it's not initially present on the page. I'm using ajax to fetch a json array and add it to select dropdowns. When one button is c ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

Explore in MegaMenu Pop-up

At my workplace, the internal web portal features a MegaMenu with a popup menu that includes a Search input field. The issue I am encountering is that when a user starts typing in the search bar and moves the mouse off of the megamenu, it disappears. It ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

What is the use of the typeof operator for arrays of objects in TypeScript?

How can I update the any with the shape of the options's object below? interface selectComponentProps { options: { label: string; value: string; }[]; } const SelectComponent: React.FC<selectComponentProps> = ({ options, }) => ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

Having issues getting Nunjucks templates to render correctly in Express

There seems to be an issue with setting up the template hierarchy in Express or possibly an error in how Nunjucks is being utilized. The goal is to have a template that includes common parts and specific pages that extend this template. It appears that the ...

Insert a new element at the current scroll position without disrupting the existing scroll or view

My goal is to replicate the functionality of the Twitter Mac client. I have a scrollable box with a fixed height and multiple blocks inside. I want to add a new block before all the others, but keep it invisible to the user so they have to scroll to the to ...