0

I am trying to get all of the videos in a YouTube playlist. The API only allows you to get 50 results at a time. I am using angular js to make the the call to web api but I cannot seem to save all of the videos to variable. When I look at the value of the variable it is undefined.

This is my function:

An example playlistId is PLFPg_IUxqnZNTAbUMEZ76_snWd-ED5en7

function getPlaylistVideos(playlistId) {
    var items = [];
    $.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key }).then(function (response) {
        items = items.concat(response.items);
        var pagetoken = response.nextPageToken;
        var previouspagetoken = "";
        while (pagetoken != null && pagetoken !== '' && previouspagetoken !== pagetoken) {
            $.get('https://www.googleapis.com/youtube/v3/playlistItems', { part: 'snippet', maxResults: 50, playlistId: playlistId, key: key, pageToken: pagetoken }).then(function(resp) {
                items = items.concat(resp.items);
                previouspagetoken = pagetoken;
                pagetoken = resp.nextPageToken;
            });
        }
    });
    return items; // This is undefined
}

What am I doing wrong? Is there a better way to do this?

user3788671
  • 1,977
  • 5
  • 29
  • 43
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – 4castle Jun 22 '16 at 18:57
  • Please, chain `.then()`. Avoid nesting callbacks – Serhii Holinei Jun 22 '16 at 19:22

0 Answers0