Last active
January 9, 2022 21:37
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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