I’m having a weird problem with my Twitch API integration. My function fetchStreamInfo should be returning JSON data, but I keep getting undefined instead. The strange part is that when I add a console log right before the return statement, I can see the data is actually there.
I’m calling this function from another part of my code where I loop through stored channel names. Here’s what I’m working with:
$('.tab-item').click(function() {
$(this).addClass('active');
if($(this).find('.show-all').length > 0) {
var container = $(this).find('.stream-list');
var savedStreams = JSON.parse(localStorage.getItem('streamers'));
var count = savedStreams.length;
var streamData = [];
for(var i = 0; i < count; i++) {
var streamInfo = fetchStreamInfo(savedStreams[i]);
// This logs undefined
console.log(streamInfo);
}
}
});
function fetchStreamInfo(streamerName) {
function StreamData(username, fullName, description, avatar, userId) {
this.username = username;
this.fullName = fullName;
this.description = description;
this.avatar = avatar;
this.userId = userId;
}
var apiUrl = 'https://api.twitch.tv/kraken/users/' + streamerName + '?client_id=abc123def456';
$.ajax({
url: apiUrl,
dataType: 'json',
error: function() {
console.log('API request failed');
},
success: function(response) {
var stream = new StreamData(
response.name,
response.display_name,
response.bio,
response.logo,
response._id
);
console.log(stream); // This shows the data correctly
return stream; // But this doesn't work as expected
}
});
}
What am I missing here? The data appears in the console inside the success callback, but the function itself returns undefined when I try to use it.