sterg sterg - 3 months ago 16
Javascript Question

Twitch TV JSON API Issue

So,I am trying to use the twitch API:
https://codepen.io/sterg/pen/yJmzrN

If you check my codepen page you'll see that each time I refresh the page the status order changes and I can't figure out why is this happening.
Here is my 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++;
})

}


});

Answer

This code will not preserve the order, but will preserve which array entry is being processed

$(document).ready(function() {
    var ur = "";
    var tw = ["freecodecamp", "nightblue3", "imaqtpie", "bunnyfufuu", "mushisgosu", "tsm_dyrus", "esl_sc2"];
    for (var i = 0; i < tw.length; i++) {
        ur = "https://api.twitch.tv/kraken/streams/" + tw[i];
        (function(j) {
            $.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>");
                }
            })
        }(i));
    }
});

This code will preserve the order fully - the layout needs tweaking though

$(document).ready(function() {
    var ur = "";
    var tw = ["freecodecamp", "nightblue3", "imaqtpie", "bunnyfufuu", "mushisgosu", "tsm_dyrus", "esl_sc2"];
    for (var i = 0; i < tw.length; i++) {
        ur = "https://api.twitch.tv/kraken/streams/" + tw[i];
        (function(j) {
            var name = $(".name").append("<li> <a href=" + "https://www.twitch.tv/" + tw[j] + ">" + tw[j] + "</a><p>" + "" + "</p></li>");
            var stat = $(".stat").append("<li></li>")[0].lastElementChild;
            console.log(stat);
            $.getJSON(ur, function(json) {
                $(".tst").append(JSON.stringify(json));
                if (json.stream == null) {
                    $(stat).text("Offline");
                } else {
                    $(stat).text(json.stream.game);
                }
            }).then(function(e) {
                console.log(e);
            }, function(e) {
                console.error(e);
            });
        }(i));
    }
});
Comments