Variable value overwritten in getJSON function

I am working on a problem in which I have to show Twitch channels that are offline and online. Here is a function that has an error:

function loadStreams(){
  for (var i = 0; i < channel_list.length; i++){
    offlineName = channel_list[i];
    console.log("offline name is: " + offlineName);
    URL = "https://wind-bow.hyperdev.space/twitch-api/streams/" + channel_list[i] + "?callback=?";
     $.getJSON(URL, function(data){
       console.log("Now offline name is: " + offlineName);
       console.log(data);
       if (data.stream !== null){
         currChannel = new Channel(data.stream.channel.display_name, data.stream.channel.status);
       }
       else {
         currChannel = new Channel(offlineName, "Offline");
       }       
       outArr.push(currChannel);
    });    
  }
  //showAll();
}

channele_list is an array of strings preloaded with channel names. It is defined as follows:

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

My code just looks at the channel list, retrieves the JSON data and returns the result and creates a new instance of the Channel object, which is defined as:

var Channel = function(name, status){
  this.name = name;
  this.status = status;
}

, else, "offlineName" channel_list, "noobs2ninjas". , Channel else, "offlineName" "noobs2ninjas". , , . CodePen, :

https://codepen.io/tcao2/pen/XNbbbm?editors=1010

+4
1

, , for (, ), , .

$.getJSON URL-, offlineName, offlineName . , . offlineName - "ESL_SC2", ajax URL-, , , - , .BUT wait offlineName "OgamingSC2"! , , , , "OgamingSC2" . , , , 1- 2- , , offlineName (noobs2ninjas), .

.. , , offlineName . - let URL offlineName, , ,

https://codepen.io/vsk/pen/LbNpBQ

, let , , , URL offlineName

(function(url,name) {
   $.getJSON(url, function(data){
   if (data.stream !== null){
     currChannel = new Channel(data.stream.channel.display_name, data.stream.channel.status);
   }
   else {
     currChannel = new Channel(name, "Offline");
   }       
   outArr.push(currChannel);
  }); 
})(URL,offlineName);

https://codepen.io/vsk/pen/rWeOGL

EDIT: ,

function hello(url,name){                //line #39
  //your code                           
}                                        //ln #53
hello(URL,offlineName);                  //ln #54

, , , , ( № 39,53,54 ) . , .

, Java, JS ( VM) , hello, ( , ), ; (URL, offlineName); hello, , getJson , , " " , [1]. URL offlineName / , , [1], , . , JS ( )

- , , , getJson , , , VM . - - ( ), , , VM , , , , , , , - . , , , , loadStreams, hello, (- ).

, , " ", .

for loop --> hello() --> getJson inner function ( )

let, http://caniuse.com/#feat=let

+5

Source: https://habr.com/ru/post/1660555/


All Articles