I'm currently working on a Spotify API project and I come to a strange behavior which I can't explain to me.
Here is my Code to which I'm now referring to:
app.post("/get-spotify-data", async (req, res) => {
var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(req.body.accessToken);
await spotifyApi.getMyCurrentPlayingTrack().then(
function (data) {
if (data.body.item) {
artists_names = [];
data.body.item.artists.forEach((artist) => {
artists_names.push(artist.name);
});
youtube
.search(data.body.item.name + data.body.item.artists[0].name)
.then((results) => {
res.json({
track_name: data.body.item.name,
album_cover: data.body.item.album.images[0].url,
artists: artists_names.join(","),
link: results.videos[0].link,
});
});
}
},
function (err) {
console.log("Something went wrong!", err);
}
);
});
So the strange behavior is that when two users call the URL "/get-spotify-data" from my Front-End at the same time (the function get's called every second) then the both users get alternately the artists from his song and the artists from the song of the other user is listening to. But the other values get sent correctly.
Might this have to do something with that I declared the artists variable? I thought as long as I won't declare it outside the function, it won't affect multiple calls.
I forgot to scope the variable.