0

I'm trying to use Spotify's API to get a list of all the saved tracks of a certain user (afterwords I need to randomize 10 songs from that list, but I'm not able to get to that point).

I'm a beginner in Node JS and still trying to understand the concepts of callbacks and promises. I'm trying to use axios to make all requests. Here's the code I have so far:

let tracks = []
function getTracks(offset, access) {
    const auth = {
        headers: { Authorization: 'Bearer ' + access }
    }
    return axios.get('https://api.spotify.com/v1/me/tracks?limit=50' + (offset > 0 ? '&offset=' + offset : ''), auth) // url changes based on offset value
        .then(result => {
            result.data.items.forEach(element => {
                tracks.push({ title: element.track.name, artist: element.track.artists });
            });
            return result.data.total;
        })
        .catch(error => {
            return error;
        });
}

router.get('/getsongs', function (req, res) {
    const access_token = req.query.access || null; // contains access token
    getTracks(0, access_token).then(data => {
        const total = (data / 50) + 1;
        for (let i = 1; i <= total; i++) {
            getTracks(i * 50, access_token).then(moredata => {
                // I'm not sure what I can put in here
                // I tried 'console.log('test')' and it does print a certain amount of times based on the loop
            });
        }    
    });
    res.send(tracks);
});

The idea behind this is to make one first request for 50 tracks, and then find the total number of tracks. After that, I'll loop a certain amount of times based off the total, and set an offset each time to get the next 50 tracks. All the tracks are added to a global list tracks, which I send to the client after all the requests are done.

I've tried many different versions of this, and no matter what I either end up with an empty list or only a list of the first 50 tracks.

How can I end up with one list containing all the tracks that I can use later in the program?

Thanks!

1 Answer 1

1

You can try using Promise.all

router.get('/getsongs', function(req, res) {
  let asyncTasks = [];
  const access_token = req.query.access || null; // contains access token
  return getTracks(0, access_token).then(data => {
      const total = data / 50 + 1;
      for (let i = 1; i <= total; i++) {
        asyncTasks.push(getTracks(i * 50, access_token));
      }
      return Promise.all(asyncTasks);
    })
    .then(listTrack => {
      console.log(listTrack)
    });
});

You are nested Promise here and this's a bad practice which is called Promise hell

getTracks(0, access_token).then(data => {
        const total = (data / 50) + 1;
        for (let i = 1; i <= total; i++) {
            //This is a promise hell 
           getTracks(i * 50, access_token).then(moredata => {

            });
        }    
    });
    res.send(tracks);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.