How to get each playlist page from Spotify API in nodejs

I am trying to get all custom playlists from spotify API and put them in a picklist. I can only access 20 playlists at a time, so I created a while loop that uses the next-page property to loop through each page of the playlists, but for some reason it ends up in an infinite loop. I am guessing that the problem is in the uri = playlist.next line as shown below. Any help would be really appreciated, here's the code:

        //Request the user information...
        $.ajax({
            url: 'https://api.spotify.com/v1/me',
            headers: {
              'Authorization': 'Bearer ' + access_token
            },
            //... Create a list of the user playlists
            success: function(user) {
              var playlistURL = 'https://api.spotify.com/v1/users/' + user.id + '/playlists';

              appendPlaylists(playlistURL);

              function appendPlaylists(nextURL) {
                if (nextURL == null) {
                  return;
                }
                //Append playlists to the menu
                $.ajax({
                    url: nextURL,
                    headers: {
                      'Authorization': 'Bearer ' + access_token
                    },
                    success: function(playlists) {
                      console.log(nextURL);

                      var i = 0;
                      while (playlists.items[i] != null) {
                        console.log(playlists.items[i].name);
                        $('.all-playlists').append('<option value="' + playlists.items[i].href + '">' + playlists.items[i].name + '</option>')
                        i++;
                      }
                      appendPlaylists(playlists.next);
                    }    
                });
              }

              //Load the logged in div.
              $('#login').hide();
              $('#loggedin').show();
            }
        });

      

+3


source to share


1 answer


Confirm JMPerez's answer :

I think the problem is you are considering blocking ajax requests when they are asynchronous. Instead of asking you for an infinite loop, make a request for the next chunk in the success callback of your previous request. Create a function that makes a request that takes an offset (or "closest" urls, and then inside that function, when the request succeeds, call yourself with the url of the next snippet.



The updated code has been added to the question above.

0


source







All Articles