Search code examples
javascriptajaxasynchronouspromisetwitch

Make sure to wait until all Ajax calls are completed before displaying the result


I make do with a problem after several tries and I rely on you to find a solution.

What I want to do is to add in a table the number of viewers of a specific streamer via the twitch api.

So I do my ajax call well:

        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)
                }            
            })
        };
 
    }

Then I push the result in my table and at the end when I do console.log I have the index, the name of the streamer and the number of viewers in my table.

The problem is that before I want to display the result, I'd like all the ajax calls to be completed before displaying. I tested with promise.all but unfortunately I didn't get anywhere.

Thank you in advance for your help.


Solution

  • using the condition below, you will be able to check if all calls are completed: (check code comments):

        viewerCount(streamer){
        let viewers = [];
        let streamerList = streamer;
        let completedCalls = 0; // init a new variable to base on
        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++; // increase completedCalls
                },
                complete: function() { // <-- here the new code 
                  if(completedCalls === streamer.length) {
                       displayYourResult();
                  }
               },
                error: function(data){
                    console.log(data)
                }            
            })
        };
    
    }