Skip to content

Instantly share code, notes, and snippets.

@thek27
Last active January 9, 2022 21:37
Show Gist options
  • Save thek27/18c371ac725f598298559d6743d66e0f to your computer and use it in GitHub Desktop.
Save thek27/18c371ac725f598298559d6743d66e0f to your computer and use it in GitHub Desktop.
Using promises to get all playlists of a spotify user with one function (requires spotify-web-api-node)
const SpotifyWebApi = require("spotify-web-api-node");
const spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(process.env.ACCESS_TOKEN);
const getPlaylists = function (userId, offset = 0, limit = 50, lists = []) {
console.log("offset", offset);
return new Promise((resolve, reject) =>
spotifyApi
.getUserPlaylists(userId, { offset, limit })
.then((data) => {
if (data.body.items.length > 0) {
const items = data.body.items.map(function (item) {
return { name: item.name, id: item.id };
});
lists = lists.concat(items);
getPlaylists(userId, offset + limit, limit, lists)
.then(resolve)
.catch(reject);
} else {
resolve(lists);
}
})
.catch(reject)
);
};
spotifyApi.getMe().then(
function (data) {
getPlaylists(data.body.id).then(function (items) {
console.log(items);
});
},
function (err) {
console.error(err);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment