I wrote this code - with the results in comments, What is going on please…
/*
Yeah… I know what you are thinking… I am not getting any response from the API, so push doesn’t push anything into the response array. but this is where is gets interesting.
‘console.log(response);’ prints an empty array in the console but when I click on the drop down next to the array, it reveals all the objects in the array as expected, with an alert that says, “This values where evaluated just now”
*/
The question in summary is, How can I successfully push each of the responses gotten from the ajax API calls into my response array?
EDIT: The ultimate goal of this function is to store all channel objects in the response array, which I intend to pass as a parameter to another function that will use that information to populate the page accordingly.
function fetchFavorites(){
// debugger;
var favorites = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var response = [];
console.log('faovrites');
for(var i = 0; i < favorites.length; i++){
var display_name = favorites[i];
$.ajax({
display_name: display_name,
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams/' + display_name,
headers: {
'Client-ID': 'my_key_goes_here' //I used the actual key while making the API calls
},
success: function(data) {
console.log(data) // logs the data I expect to push into the console without any issues.
data.display_name = this.display_name;
response.push(data); //push response to array of responses (objects)
},
error: function(xhr, status, error) {
console.log(xhr, status, error);
},
cache: false
});
}
alert(response.length); // this alerts 0
console.log(response); // This prints an empty array.
/*
Yeah... I know what you are thinking.... I am not getting any response so push doesn't push anything.
but this is where is gets interesting.
'console.log(response);' prints an empty array in the console, but when I click on the drop down next to the array,
it reveals all the objects in the array as expected, with an alert that says, "This values where evaluated just now"
*/
}