Twitch API function returns undefined instead of expected JSON data

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.

ajax doesn’t wait for a response - your return is stuck in the success callback, not the main function. you’ve got two options: use $.when() or make fetchStreamInfo return the ajax promise directly. then use .done() in your loop instead of expecting a return value.

You’ve hit a classic async JavaScript problem. Your fetchStreamInfo function doesn’t return anything - that return stream is stuck inside the AJAX success callback, which fires after your main function already finished and returned undefined.

I’ve been there. Same exact issue when I started with APIs. Quick fix: make fetchStreamInfo take a callback parameter, then call that callback with your stream data inside the success handler. You could also switch to promises or async/await, but that’d mean bigger changes.

The main thing - AJAX calls don’t block. Your loop keeps running before those API responses come back.

This happens because AJAX is asynchronous. Your fetchStreamInfo function starts the $.ajax call but doesn’t wait for it to finish. Since there’s no return statement in the main function, it returns undefined right away. I hit this same problem last year with external APIs. The return inside your success callback only returns to that callback - not to fetchStreamInfo. By the time the API responds, your calling code has already moved on. You should restructure this with promises. Wrap your AJAX call in a new Promise and resolve it with the stream data. Then use .then() in your loop or switch to async/await. This keeps your code clean and handles the async flow properly.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.