首页 > 解决方案 > 确保等到所有 Ajax 调用都完成后再显示结果

问题描述

经过几次尝试,我解决了一个问题,我依靠你找到解决方案。

我想要做的是通过 twitch api 在表格中添加特定流媒体的观众数量。

所以我把我的ajax调用做得很好:

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

然后我将结果推送到我的表格中,最后当我执行 console.log 时,我有索引、流媒体的名称和表格中的观众数量。

问题是在我想显示结果之前,我希望在显示之前完成所有 ajax 调用。我用 promise.all 进行了测试,但不幸的是我没有得到任何结果。

预先感谢您的帮助。

标签: javascriptajaxasynchronouspromisetwitch

解决方案


使用以下条件,您将能够检查是否所有调用都已完成:(检查代码注释):

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

}

推荐阅读