Hello, fellow campers!
I’m stuck with Javascript code for the challenge, here it is:
var users = ['ESL_SC2',
'OgamingSC2',
'cretetion',
'freecodecamp',
'storbeck',
'habathcx',
'RobotCaleb',
'noobs2ninjas',
'brunofin',
'comster404'],
baseURL = 'https://api.twitch.tv/kraken';
function getUsersInfo(_users, _URL) {
var arr = [];
_users.forEach(function(u) {
var info = {};
var getUsers = $.getJSON(_URL + '/users/' + u + '?callback=?');
var getStreams = $.getJSON(_URL + '/streams/' + u + '?callback=?');
getUsers.done(function(data) {
info.name = data.display_name;
data.logo === null ? info.logo = 'PLACEHOLDER' : info.logo = data.logo;
info.url = 'https://twitch.tv/' + data.name;
});
getStreams.done(function(data) {
info.active = true;
if (data.stream === null) {
info.status = 'Offline';
} else if (data.status === 422) {
info.status = 'Offline';
info.active = false;
} else {
info.status = "Online";
info.game = data.stream.game;
info.channel_status = data.stream.channel.status;
};
});
arr.push(info);
});
return arr;
}
I’m trying to execute function getUsersInfo, assign the result to variable and then iterate over it like so:
var result = getUsersInfo(users, baseURL);
result.forEach(function(obj) {
console.log(obj.name);
});
But it always return undefined. Looks like ajax response come after my function call and loop executes, so function return an array of empty objects. How to get around it?