0

For the last couple of hours, I have been trying to solve a FreeCodeCamp challenge (specifically, http://www.freecodecamp.com/challenges/zipline-use-the-twitch.tv-json-api) in which we are supposed to get info from Twitch, via JSON. I have been trying to get some info from a $.getJSON request. I realized the issue with async calls, but I seem to still be running into some issues. Note: users is simply an array of Twitch users.

My Code:

var users = ["freecodecamp", "storbeck", "terakilobyte", "srkevo1", "habathcx","RobotCaleb","comster404","brunofin","thomasballinger","noobs2ninjas","beohoff"];

var online=[];
var offline= [];

for(var i =0; i < users.length; i++){
    var StreamURL = "https://api.twitch.tv/kraken/" +"streams/" + users[i] + "?callback=?";
    getOnline(StreamURL).then(function(returndata){
       online.push(returndata.data);
       console.log(online);
    });
}

function getOnline(val){
    return $.getJSON(val).then(function(data){
        return{
           stream:data.stream,
           data:data._links
        }
    });
}  

Everything seems fine when I log the users in the actual for loop (i.e. the console.log of online successfully gets the info from all the users) but when I exit the loop, and print the same thing, I get an empty array. How do I ensure that this data is preserved?

hichris123
  • 10,145
  • 15
  • 56
  • 70
svsav
  • 828
  • 3
  • 12
  • 29
  • 2
    *"How do I ensure that this data is preserved?"* It is preserved, but you are logging the array **before** the Ajax calls have returned. Why do you think you have to provide a callback? See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/218196) – Felix Kling Jul 21 '15 at 03:28
  • I noticed this as well, since when I put a console.log call outside the loop, it appeared first. What can I do to ensure the array is logged after the calls have returned. – svsav Jul 21 '15 at 03:29
  • See the duplicate, http://stackoverflow.com/q/5627284/218196, or these: https://stackoverflow.com/search?tab=votes&q=[jquery]%20multiple%20ajax – Felix Kling Jul 21 '15 at 03:35
  • Alright, thanks for the help! – svsav Jul 21 '15 at 03:39

0 Answers0