0

I'm using an API to get information about some Twitch channels and for every channel, I'm creating an object which contains this information and I push every object into an array. When I log the array in the console I can see every object, but then I log the array's length it shows 0.

var streams = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var url = "https://wind-bow.glitch.me/twitch-api/streams/";

var card = `<div class="card">
    <div class="card-body row">
        <div class="col-sm-1">
            <img width="48" src="logo" alt="No logo available">
        </div>
        <div class="col-sm-11">
            <a target="_blank" href="link">name</a>
            <p>state</p>
        </div>
    </div>
</div>`;

var channels = [];

function add_channel(channel) {
    /*
    Add a new bootstrap.card with the given channel to
    the .channels-list
    */

    var current_card = card;
    current_card = current_card.replace("name", channel.name);
    current_card = current_card.replace("link", channel.link);
    current_card = current_card.replace("logo", channel.logo);
    current_card = current_card.replace("state", channel.state);
    $('.channels.list').append(current_card);
}

function gather_info() {
    /* Populate the channels array with information for every streamer. */

    for (var i = 0; i < streams.length; i++) {
        (function(index) {
            $.getJSON(url + streams[index], function(data) {
                if (data.stream == null) {
                    var channel = {};
                    channel.name = streams[index];
                    channel.state = "Offline";
                    channel.link = "http://twitch.tv/" + streams[index];
                    channel.logo = "none";
                    channels.push(channel);
                }
                else {
                    var channel = {};
                    channel.name = data.stream.channel.status;
                    channel.link = data.stream.channel.url;
                    channel.logo = data.stream.channel.logo;
                    channel.state = "LIVE";
                    cchannels.push(channel);
                }
            });
        })(i);
    }
}

$(function() {
    gather_info();
    console.log(channels);
    console.log(channels.length);
});

I push the channels from the gather_info function and I call it at the bottom of the code together with those two logs. What am I doing wrong and why my channels array is not filling up?

Xyntell
  • 155
  • 1
  • 14

0 Answers0