javascript - Accessing array / scope of variable -
this question has answer here:
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
Post a Comment