Reputation: 2155
I am completing an exercise from Free Code Camp that requires that I interact with the TwitchTV API.
I am using a jQuery file which I include in my HTML file right before the closing body tag - please see below for the code.
I am using the last line of the code to check that I am getting the data.
The code work fine when I first boot up the browser. However, if I refresh (to check my work after making changes), the output to the console will be an empty array, which is not what I expected.
Can someone help me figure out why this behavior occurs? Also, how would I be able to fix it?
$(document).ready(function() {
// on document ready
var baseEndpoint = "https://api.twitch.tv/kraken/streams/"
var users = ["medrybw", "freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","comster404","brunofin","thomasballinger","noobs2ninjas","beohoff"]
var JSONP = "?callback=?"
// all users
var allUsers = [];
// for each user
users.forEach(function(currUser) {
// make a request to the API
$.getJSON(baseEndpoint + currUser + JSONP, function(data) {
// gather and format information for user
var user = {};
// userName
user["userName"] = currUser;
// streamStatus
if (data["stream"] === null) {
user["streamStatus"] = "user-off";
}
else {
user["streamStatus"] = "user-on";
}
// img
if (user["streamStatus"] === "user-on") {
user["img"] = data["stream"]["channel"]["logo"];
}
else {
user["img"] = "http://static-cdn.jtvnw.net/jtv-static/404_preview-300x300.png";
}
allUsers.push(user);
});
});
$(document).ajaxComplete(function() {
console.log(allUsers);
});
});
Upvotes: 0
Views: 74
Reputation: 722
The the thing about AJAX is the asynchronous part. Check this answer out about that What does Asynchronous means in Ajax?.
In your code example you are asking JS to show the value of the users array before the api calls have completed, so its empty.
In this plunker http://plnkr.co/edit/dKfuP9XDhidWMskmiop3?p=preview you can see I have used an event binder to output the user array each time an AJAX call is completed.
$( document ).ajaxComplete(function() {
console.log(allUsers);
});
Output this way you can see the array build as each call to the api is returned.
Good luck!
Upvotes: 1