有时,当通道实际脱机时,状态不准确地在线显示,反之亦然。有时第一个频道显示不正确。有什么原因吗?
代码笔:https://codepen.io/Wizikal/full/NvJpZo/
Javascript部分:
$(document).ready(function() {
var array = ["tsm_dyrus", "summit1g", "shroud", "freecodecamp", "imaqtpie", "GreekGodX", "huni", "faker", "loltyler1"];
for (var i = 0; i < array.length; i++) {
$.getJSON('https://wind-bow.glitch.me/twitch-api/streams/' + array[i] + '?callback=?', function(result) {
if (result.stream === null) {
status = 'offline';
} else if (result.stream === undefined) {
status = 'offline';
} else {
status = 'online';
};
});
$.getJSON('https://wind-bow.glitch.me/twitch-api/users/' + array[i],
function(twitch) {
body = "<div class = 'row text-center " + status + "' id = 'line'><div class = 'col-md-4' id = 'image'><img src = '" + twitch.logo + "'></div><a href = 'https://www.twitch.tv/" + twitch.name + "' class = 'col-md-4' target = 'blank'><p id = 'title'>" + twitch.name + "</p></a><p class = 'col-md-4' id = 'status'>" + status + "</p></div>";
$('#main').append(body);
});
}
$('#all').on('click', function() {
$('.offline').show();
$('.online').show();
})
$('#online').on('click', function() {
$('.offline').hide();
$('.online').show();
})
$('#offline').on('click', function() {
$('.offline').show();
$('.online').hide();
})
})发布于 2017-09-05 01:56:15
几个问题。您正在使用一个getJSON调用获取状态,然后使用另一个调用获取用户信息,其中一个将在另一个之前完成(您还没有告诉他们等待另一个。您还将状态存储在全局变量中,以便在调用之间共享这些值。
相反,您可以将每个请求存储到一个变量中,将每个请求传递给jQuery.when(),然后在两个请求完成后进行解析。然后,您可以在相同的然后()回调中使用这两个结果。
for (var i = 0; i < array.length; i++) {
let streamRequest = $.getJSON('https://wind-bow.glitch.me/twitch-api/streams/' + array[i] + '?callback=?');
let userRequest = $.getJSON('https://wind-bow.glitch.me/twitch-api/users/' + array[i]);
$.when(streamRequest,userRequest)
.then(function(statusResult,twitch){
//when() results get stored in arrays, [data,status,jqXHR]
statusResult = statusResult[0]; twitch = twitch[0];
//undefined / null are both falsy so just do a single test
var status = statusResult.stream ? 'online' : 'offline';
$('#main').append("<div class = 'row text-center " + status + "' id = 'line'><div class = 'col-md-4' id = 'image'><img src = '" + twitch.logo + "'></div><a href = 'https://www.twitch.tv/" + twitch.name + "' class = 'col-md-4' target = 'blank'><p id = 'title'>" + twitch.name + "</p></a><p class = 'col-md-4' id = 'status'>" + status + "</p></div>");
});
}https://stackoverflow.com/questions/46045879
复制相似问题