Use the Twitchtv JSON API issue


#1

Hello, I’m trying to solve the Twich API challange but I’m a little stuck.

$(document).ready(function(){
  var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  
  var streamInfo = "https://wind-bow.glitch.me/twitch-api/streams/";
  var channelInfo = "https://wind-bow.gomix.me/twitch-api/channels/";
  
  for(var i = 0; i < streamers.length; i++){
  
  streamInfo = "https://wind-bow.glitch.me/twitch-api/streams/";
  channelInfo = "https://wind-bow.gomix.me/twitch-api/channels/";
    
  streamInfo += streamers[i];
  channelInfo += streamers[i];
    console.log(streamers[i]);
  
  streamInfo += "?callback=?";
  channelInfo += "?callback=?";
 
$.getJSON(streamInfo, function(data){
    $.getJSON(channelInfo, function(data1){
        $("#logo").prepend("<img src='" + data1.logo + "'>");
    });
  });  
  }
});

This code will output the same logo (of the last element of the array) 7 times.
so the question is:

Why is it that when I look at channeIInfo outsite the getJSON function it gets the right URL(using the array elements one by one) but when I look at the same variable inside the function it always gets the last element of the array ? Even the first time it goes through


#2

the same channelInfo variable is being reassigned in the loop - any async callback in the loop unexpectedly using last value of channelInfo ran after the loop was complete - the fix is to declare channelInfo inside the loop like this

let channelInfo = "https://wind-bow.gomix.me/twitch-api/channels/"
channelInfo += streamers[i]

This post is related


#3

That solved the problem, thanks a lot!