Overwhelmed by twitch TV project(multiple ajax requests, callbacks/promises)

Hello,

I have completed most of what is necessary for the Twitch TV project and found it pretty easy up until trying to fufill this user story:
I will see a placeholder notification if a streamer has closed their Twitch account (or the account never existed). You can verify this works by adding brunofin and comster404 to your array of Twitch streamers.

For the rest of the project I have used twitch-api/streams/
api call, but now need to use twitch-api/users/ to find out if the streamer exists or not.Needing multiple API calls has introduced me to the importance of understanding asynchronous code and I am now pretty lost trying to learn about callbacks/promises and feel completely out of my depth to be honest and do not know which way to proceed.

what would be the best way to go about fulfilling this user story?

When I did it, I created a getStreamer function which I called for every streamer in the array. It looked something like htis:

$.getJSON('https://api.twitch.tv/kraken/channels/' + streamer + '?callback=?', function(object) {
  if (object.status === 422) { //Invalid Channel
    // ...
  }
  return;
});

$.getJSON('https://api.twitch.tv/kraken/streams/' + streamer + '?callback=?', function(object) {
  if (object.stream === null) { //Channel Offline
    $.getJSON('https://api.twitch.tv/kraken/channels/' + streamer + '?callback=?', function(object) {
      // ...
      return;
    });
  } else { //Channel Live
    // ...
        return;
  }
});

By now the twitch API has changed, and I know a lot more about asynchronous JavaScript, so I would probably do it a lot differently.

If I were you, I would start learning more about async. Watch this if you haven’t already: http://thenetninja.co.uk/courses/asynchronous-javascript-tutorial.

Also if you don’t mind using babel, you can try out the snazzy new async funtions or fetch:

async function getStatus() {
  try {
    let json = await getData();
    // handle data...
  }
  catch (err) {
    // offline
  }
}
fetch('link', {
	method: 'get'
}).then(function(response) {
	
}).catch(function(err) {
	// Error :(
});
2 Likes

I nested API calls. https://www.youtube.com/watch?v=oZ9KTppX4T8&list=PLcwcsiRRNFZXkPzkge5yBKPH9DowN8sqX

1 Like

thanks guys. I ended up successfully nesting getJSON callbacks. Is definetely not the most elegant code I have written but it works. :slight_smile: