0

So different API calls are necessary to get all of the data I need for the feed objects, so I have two seperate API calling functions. The first gets the basic information on each feed and throws each into an array as an object. The second function (finishArray()) adds 2 properties to each object, the URL and the status. For whatever reason though, my the second function isn't getting called. I can't figure out why.

The second function is the finishArray() function, I had planned on it being called after the original forEach loop is completed that makes the base array.

var feeds = ["Towellie", "TrumpSC", "TeamSp00ky", "TwitchPlaysPokemon", "Widgitybear", "AriaBlarg", "TheMexicanRunner", "OPNerd", "rabbitbong", "Wingsofdeath", "MedryBW"];

function feedStatus(feedTitle, onOrOff, gamePlayed) {
  this.title = feedTitle;
  this.streaming = onOrOff;
  this.url = "https://www.twitch.tv/" + this.title;
  this.game = gamePlayed;
};

var feedStatusArray = [];

var finishArray = function() {
  feedStatusArray.forEach(function(feed) {
    $.getJSON('https://api.twitch.tv/kraken/channels/' + feed.title + '?callback=?', function(data) {
      feed.logo = data.logo;
      feed.status = data.status;
    });
  });
}

$(document).ready(function() {
  feeds.forEach(function(feedName) {
    $.getJSON('https://api.twitch.tv/kraken/streams/' + feedName + '?callback=?', function(data) {
      if (data.stream === null) {
        feedStatusArray.push(new feedStatus(feedName, data.stream));
      } else {
        feedStatusArray.push(new feedStatus(feedName, data.stream, data.stream.game))
      }
    });

  });
  finishArray();
})
Cœur
  • 37,241
  • 25
  • 195
  • 267
Scriptomaniac
  • 207
  • 1
  • 2
  • 10
  • 1
    Why do you think it's not being called? What happens if you put `alert(feedStatusArray.length)` in it? – Barmar Apr 15 '16 at 23:59
  • Did your copy-paste mess up or do you not have a semi-colon at the end? – Dresden Apr 15 '16 at 23:59
  • 4
    Remember that AJAX requests are **asynchronous**, so your `feedStatusArray` is not populated yet when `finishedArray()` is called. You will need to compile a list of promises returned from each `getJSON` function, and when all the promises have been fulfilled (technical term would be a *resolved* promise), you can then execute `finishArray()`. – Terry Apr 15 '16 at 23:59
  • @MikeS Nope, semi-colons in JS are actually optional (in most cases). – Terry Apr 16 '16 at 00:00

0 Answers0