[SPOILER] Twitch and promises

[SPOILER] Twitch and promises
0

#1

First, here’s what I have so far.

var streamers = [/* streamers */];

streamers.forEach(streamer =>
  Promise.resolve(ajax(`https://api.twitch.tv/kraken/streams/${streamer}`))
  .then(function fulfilled(data) {
    if (!data.stream) {
      // Make another request for channel info for offline streamers
      return Promise.resolve(ajax(data._links.channel));
    }

    // For online streamers, just use what comes with the data
    return Promise.resolve(data.stream.channel);
  })
  .then(function fulfilled(data) {
    $("#streamers-offline").append(/* append stuff */);
  })
  .catch(function rejected(err) {
    // This is where closed accounts are processed.
    $("#streamers-invalid").append(/* append stuff */);
  })
);

I have three lists in the HTML, namely #streamers-online, #streamers-offline and #streamers-invalid. With the current code both online and offline streamers are appended to the offline list, which is not right.

I could just add

data.stream.channels.isOnline = true;

before the second return in the first .then, and then modify $("#streamers-offline") to something like

$(data.isOnline ? "#streamers-online" : "#streamers-offline")

but it feels hackish.

Any thoughts?


Stuck on twitch tv project for 2 weeks
#2

Nevermind. I think I’ll settle with a “better” hack (if it’s a hack at all).

var streamers = [/* streamers */];

streamers.forEach(streamer =>
  Promise.resolve(ajax(`https://api.twitch.tv/kraken/streams/${streamer}`))
  .then(function fulfilled(data) {
    if (!data.stream) {
      // Make another request for channel info for offline streamers
      return Promise.resolve(ajax(data._links.channel));
    }

    $("#streamers-online").append(/* append stuff */);

    // "Break" the promise chain after rendering online streamer.
    return new Promise((resolve, reject) => { });
  })
  .then(function fulfilled(data) {
    $("#streamers-offline").append(/* append stuff */);
  })
  .catch(function rejected(err) {
    // This is where closed accounts are processed.
    $("#streamers-invalid").append(/* append stuff */);
  })
);

#3

Not as much of a hack as what I recall I did. I actually went through them all in parallel using Bluebird as I recall. The Twitch API leaves much to be desired, I found.

Glad it works!