I am coding an app using twitch.tv API, for which i need to make multiple getJSON() calls for different users. Is there any explanation for the following output.
//users array contains the list of users for which data is fetched
var users = ["freecodecamp", "brunofin", "storbeck", "medrybw", "comster404", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff"];
When using the simple for loop:
for (var i = 0; i < users.length; i++) {
var user = users[i];
$.getJSON("https://api.twitch.tv/kraken/streams/" + user + "?callback=?", function(json) {
var add = user;
if(json.status === 422) {
add = add + ' ' + "Closed";
} else {
if (json.stream === null) {
add = add + ' ' + "Offline";
} else {
add = add + ' ' + json.stream.game;
}
}
$("#userList").append("<div>" + add + "</div>");
});
};
Output:
beohoff Closed
beohoff Offline
beohoff Offline
beohoff Offline
beohoff StarCraft: Brood War
beohoff Offline
beohoff Offline
beohoff Offline
beohoff Offline
beohoff Closed
beohoff Offline
When using forEach:
users.forEach(function(user) {
$.getJSON("https://api.twitch.tv/kraken/streams/" + user + "?callback=?", function(json) {
var add = user;
if(json.status === 422) {
add = add + ' ' + "Closed";
} else {
if (json.stream === null) {
add = add + ' ' + "Offline";
} else {
add = add + ' ' + json.stream.game;
}
}
$("#userList").append("<div>" + add + "</div>");
});
});
Output:
brunofin Closed
comster404 Closed
storbeck Offline
terakilobyte Offline
freecodecamp Offline
medrybw StarCraft: Brood War
thomasballinger Offline
RobotCaleb Offline
noobs2ninjas Offline
habathcx Offline
beohoff Offline
Are the ajax calls made sequentially in case of forEach or is there something else ?