Twitch app i'm stuck please help

Twitch app i'm stuck please help
0

#1

Hi Everyone,

I seem to be stuck when retrieving information from twitch API. I am able to manually get the information i need, but when i use a for loop to retrieve info for multiple different channels it only gives me data for the first channel logo in the loop, the chName and chUrl show up undefined. I’ve been banging my head at it for many hours and was wondering if anyone can point out what i am doing wrong?

Thank you in advance for you help!

$(document).ready(function(){
  var clientId = "1hgu9o71td72uteenuhdjeu”
  var stream = "https://api.twitch.tv/kraken/streams/"
  var channel = "https://api.twitch.tv/kraken/channels/"
  var channelArr = ["streamerhouse", "freecodecamp", "ESL_SC2", "OgamingSC2", "storbeck", "noobs2ninjas"];
  var logo = "";
  var status = "";
  var description = "";
  var chName = "";
  var chUrl = "";
  

for(var i = 0; i < channelArr.length; i++){
 $.ajax({
 type: 'GET',
 url: stream + channelArr[i],
 headers: {
   'Client-ID': clientId
 },
 success: function(data) {
   dataA = data;
   $.ajax({
 type: 'GET',
 url: channel + channelArr[i],
 headers: {
   'Client-ID': clientId
 },
 success: function(data1) {
   
   logo = data1.logo;
   chName = data1.display_name;
   chUrl = data1.url;
   
   if(data.stream === null){
     status = "<div class='row online'>";
     description = "Offline"
   }else{
     status = "<div class='row offline'>";
     description = data.stream.channel.status;
   
 }
console.log(chName)
   console.log(logo)
   console.log(chUrl)
   
   
    //$(".mid").append(status+"<div class='col col-4'><img class='logo' src="+logo+">"+"<p class='text'><a href="+chUrl+"target='_blank'>"+chName+"</a></p></div><div class='col col-8'><p class='text'>"+description+"</p></div></div>");
   
   
   }
     
  });
   
 }
});
}
 

});

#2

Because you are using var i instead of let i, i does not retain its value within the $.ajax call, because the for loop finishes before the first response even comes back from the call to https://api.twitch.tv/kraken/channels/streamerHouse.

Why? Because the $.ajax is asynchronous which means it does not prevent other synchronous code from continuing to run while the $.ajax function is waiting for a response to come back from a particular call.


#3

It works now and learned something new today

Thank you Randelldawson!!