Twitch TV Viewer Help

Twitch TV Viewer Help
0

#1

I have a problem with displaying Channel list. It comes as ‘undefined’. Please find the project link here

The Jquery script is as below:

var listChannel = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

var myUrl = 'https://wind-bow.hyperdev.space/twitch-api/streams/'


$(".myContainer").append("<div class = 'row'>");


for (var i =0; i<listChannel.length; i++){
		
		
		
			$.ajax({
			method: 'GET',
			url: myUrl+listChannel[i],
			dataType : "jsonp",
			callback : "?",
			success: function(data){
						if(data.stream){
							
							$(".myContainer").append("<div class = 'col-md-4'>"+listChannel[i]+"</div>");
							$(".myContainer").append("<div class = 'col-md-4' style='color:green'>ONLINE</div>");	
							$(".myContainer").append("<div class = 'col-md-4'><a class='button' href="+data.stream.channel.url+">WATCH</a> </div>")
							
							
			
						} else{
							
							$(".myContainer").append("<div class = 'col-md-4'>"+listChannel[i]+"</div>");
							$(".myContainer").append("<div class = 'col-md-4'>OFFLINE</div>");	
							$(".myContainer").append("<div class = 'col-md-4'>#</div>")
							
						};
		
		
		
					},
			error: function(error){
		
						alert('error');
				}
		});
		
		
		
		
     
}

 $(".myContainer").append("</div>");

#2

The problem is with JS’s asynchronous nature. The $.ajax call is async while the for loop is async, so by the time the first callback for the $.ajax call is invoked, the for loop would have finished.

One of the solutions is to wrap your $.ajax call in anonymous self-envoking function (closure) and pass in the value of i,

e.g.

(function (i) {
//your Ajax call here

})(i);


#3

Thanks @vdineva your suggestion helps.