Twitch TV Viewer Help

Twitch TV Viewer Help


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 = ''

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

for (var i =0; i<listChannel.length; i++){
			method: 'GET',
			url: myUrl+listChannel[i],
			dataType : "jsonp",
			callback : "?",
			success: function(data){
							$(".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="">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){



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,


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



Thanks @vdineva your suggestion helps.