所以,我正在尝试使用 twitch API:
https://codepen.io/sterg/pen/yJmzrN
如果您检查我的 codepen 页面,您会发现每次刷新页面时状态顺序都会发生变化,并且我无法弄清楚为什么会发生这种情况。
这是我的 JavaScript:
$(document).ready(function(){
var ur="";
var tw=["freecodecamp","nightblue3","imaqtpie","bunnyfufuu","mushisgosu","tsm_dyrus","esl_sc2"];
var j=0;
for(var i=0;i<tw.length;i++){
ur="https://api.twitch.tv/kraken/streams/"+tw[i];
$.getJSON(ur,function(json) {
$(".tst").append(JSON.stringify(json));
$(".name").append("<li> <a href="+"https://www.twitch.tv/"+tw[j]+">"+tw[j]+"</a><p>"+""+"</p></li>");
if(json.stream==null){
$(".stat").append("<li>"+"Offline"+"</li>");
}
else{
$(".stat").append("<li>"+json.stream.game+"</li>");
}
j++;
})
}
});
最佳答案
$.getJSON()
异步工作。在结果返回之前,不会返回 JSON。 API 的返回顺序可能与请求的顺序不同,因此您必须处理这个问题。
实现此目的的一种方法是使用 Promise API 以及 $.when()
将所有请求捆绑为一个大 promise ,该 promise 将作为一个整体成功或失败。这还可以确保响应数据按预期顺序返回到您的代码。
试试这个:
var channelIds = ['freecodecamp', 'nightblue3', 'imaqtpie', 'bunnyfufuu', 'mushisgosu', 'tsm_dyrus', 'esl_sc2'];
$(function () {
$.when.apply(
$,
$.map(channelIds, function (channelId) {
return $.getJSON(
'https://api.twitch.tv/kraken/streams/' + encodeURIComponent(channelId)
).then(function (res) {
return {
channelId: channelId,
stream: res.stream
}
});
})
).then(function () {
console.log(arguments);
var $playersBody = $('table.players tbody');
$.each(arguments, function (index, data) {
$playersBody.append(
$('<tr>').append([
$('<td>'),
$('<td>').append(
$('<a>')
.text(data.channelId)
.attr('href', 'https://www.twitch.tv/' + encodeURIComponent(data.channelId))
),
$('<td>').text(data.stream ? data.stream.game : 'Offline')
])
)
})
})
});
https://codepen.io/anon/pen/KrOxwo
在这里,我使用$.when.apply()
使用$.when
使用数组,而不是参数列表。接下来,我使用$.map()
将 channel ID 数组转换为每个 ID 的 Promise 数组。之后,我有一个简单的辅助函数来处理正常响应( res
),提取相关的流数据,同时附加channelId以供稍后使用。 (如果没有这个,我们将不得不返回原始数组来获取 ID。您可以这样做,但在我看来,这不是最佳实践。我更愿意将数据与响应一起保留,以便稍后的重构不太可能破坏某些东西。这是一个偏好问题。)
接下来,我有一个.then()
处理程序获取所有数据并循环遍历它们。该数据作为函数的参数返回,因此我只需使用 $.each()
迭代每个参数,而不必将它们命名出来。
我还对处理 HTML 的方式进行了一些更改。您会注意到我正在使用 $.text()
和$.attr()
设置动态值。这可以确保您的 HTML 有效(因为您根本没有真正将 HTML 用于动态位)。否则,某人的用户名可能是 <script src="somethingEvil.js"></script>
它会在您的页面上运行。这完全避免了这个问题。
关于javascript - Twitch TV JSON API 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39197448/