javascript - 确保等到所有 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 进行了测试,但不幸的是我没有得到任何结果。
预先感谢您的帮助。
解决方案
使用以下条件,您将能够检查是否所有调用都已完成:(检查代码注释):
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)
}
})
};
}
推荐阅读
- elasticsearch - 当我重新启动服务器时,Elasticsearch 不会自动启动
- bash - 需要帮助将源目录添加到 bash 脚本
- c++ - 既然我们有内联变量,还有用 extern const 吗?
- c++ - 我在 OpenGL 中显示图像时遇到问题
- generics - Dagger MutableLiveData 标识符
- sql - 将数组放入 WHERE IN 子句 Ruby on Rails
- sql - 如何获得每个岛屿的第一排和最后一排?
- javascript - 如何在数组Javascript上查找字符串的索引
- javascript - 当我修改 img src 时,jsPDF 不打印 img
- python - 如何在python中使用地理编码器获取邮政编码,提供地理坐标