0

Working on a simple web app using Twitch.tv API. I have a factory that's getting top 5 videos for each of the top 10 games. I'm using a for-loop to iterate through each game, and a GET request for each iteration with a promise to push the data into an array.

Problem is: I'm getting the data back fine, but the data isn't being pushed into the array (videoResults) I want to collect it. Is it something that has to do with having a promise within a loop?

(I also realize since the requests will come back asynchronously, they will be out of order, but I'll figure out how to push them into specific indexes later I guess, right now I just want to figure how to get them into the array first).

factory.getTwitchVidData = function(twitchData) {
    // get top 10 games data from other factory
    var gamesArray = factory.getTopGames(twitchData);
    var videoResults = [];
    // for each game, get top 5 videos
    for (var i = 0, ii = gamesArray.length; i < ii; i++) {
        $http.get('twitch_topvids.php?gamename=' + gamesArray[i])
        .success(function(response) {
            videoResults.push(response);
            console.log(response);
        });
    }
    console.log(videoResults);
    return videoResults;
};
John Vu
  • 85
  • 8
  • Well, it *is* pushed on the array, but you are logging and returning the array when it is still empty. Didn't you note yourself that they're asynchronous?! – Bergi Jan 28 '15 at 17:30
  • Gotcha! Thanks for pointing that out. Seems I didn't think about it hard enough and it was just staring back at me. I moved the log into the promise and it's logging that the array is being filled up. – John Vu Jan 28 '15 at 17:45

0 Answers0