I am trying to create a promise with a looped API request to Spotify. Spotify works so that I can only get 100 tracks at a time, so I check if there are more and rerun the function until all the tracks are appended to the "items" list. Right now, the promise resolves after 1 request, but I need to to resolve after all the requests are made. My code:
function getItems(myUrl) {
return new Promise((resolve, reject) => {
let items = []
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
// use the access token to access the Spotify Web API
var token = body.access_token;
var options = {
url: myUrl,
headers: {
'Authorization': 'Bearer ' + token
},
json: true
};
request.get(options, function(error, response, body) {
if (error) return reject(error);
for (var item of body['items']) {
items.push(item)
}
if (response.body.next != null) {
getItems(response.body.next)
}
resolve(items)
})
} else {
reject(error)
}
})
return items
})
}
getItems('https://api.spotify.com/v1/playlists/1vZFw9hhUFzRugOqYQh7KK/tracks?offset=0')
.then(res => console.log(res))