Twitch.tv API在线/离线不准确

时间:2017-09-05 01:39:55

标签: javascript

当频道实际离线时,有时状态不准确在线显示,反之亦然。有时第一个通道无法正确显示。有什么理由吗?

密码笔:https://codepen.io/Wizikal/full/NvJpZo/

Javascript Part:

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

1 个答案:

答案 0 :(得分:0)

一些问题。您正在使用一个getJSON调用来获取状态,然后另一个获取用户信息,一个将在另一个之前完成,即您没有告诉他们等待另一个。您还将状态存储在全局变量中,以便在调用之间共享值。

相反,您可以将每个请求存储到一个变量中,将每个请求传递给jQuery.when(),然后在两个请求完成时解析。然后,您可以在相同的then()回调中使用这两个结果。

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