javascript - Accessing array / scope of variable -


i attempting populate array , use later. getting "undefined" result when try accessing objects @ indexes.

$(document).ready(function() {    var streamers = ["freecodecamp", "geoffstorbeck", "terakilobyte"];    var cb = '?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?';   var url = 'https://api.twitch.tv/kraken/';   var result = {};     streamers.foreach(function(stream)   {     $.getjson(url + 'streams/' + stream + cb).success(function(data)     {         var streaming = (data.stream === null) ? false : true;         result.push(stream + " - " + streaming);     });   });    alert(result[0]);   alert(result[1]);   alert(result[2]); }); 

what need callback, getting server happens in asynchronous processes, mean code continues executing , adds array when returned. want script alert things when completed task, why call call back, call passed function back (aka when it's done).

$(document).ready(function() {      var streamers = ["freecodecamp", "geoffstorbeck", "terakilobyte"];      var cb = '?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?';    var url = 'https://api.twitch.tv/kraken/';    // should initialised array, not object!    var result = [];        function callback(){      // add line reduce amount of alerts      if(result.length !== 3) return;      alert(result[0]);      alert(result[1]);      alert(result[2]);    }        streamers.foreach(function(stream){      $.getjson(url + 'streams/' + stream + cb).success(function(data){          var streaming = (data.stream === null) ? false : true;          result.push(stream + " - " + streaming);          callback();      });    });  });


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -