welcome to my first SO question. I am trying to make a call to Spotify's API from my Express backend, and I am unable to get the data returned properly. The API request is not the problem - the correct information gets returned, I just can't seem to retrieve that info.
Here is the route which calls the getOldTracks
function that contains the API call.
router.post("/remix", async (req, res) => {
// Fetch song information
const oldTracks = await getOldTracks(req.body.playlistId, req.user.username).then((data) => {
console.log('returned to original call',data);
return data;
}).catch((err) => {console.log('this is an error',err)});
});
I originally tried to directly return the setUpSpotifyApi
function, but it would just return a pending promise that would just resolve into undefined. I am trying it with trackList
to try to see the order of what gets called.
const getOldTracks = async (playlistId, userName) => {
let trackList = null;
await setUpSpotifyApi(userName)
.then((spotifyApi) => {
spotifyApi.getPlaylist(playlistId).then(
(data) => {
console.log('in spotify api call',data.body.tracks.items)
trackList = data.body.tracks.items;
// return data.body.tracks.items;
},
(err) => {
console.log("Error grabbing playlist", err);
}
);
})
.catch((error) => {
console.log(error);
});
console.log('after await',trackList);
return trackList
};
Here is what the console shows. This is for a playlist with no tracks, so the empty array is correct
after await null
returned to original call null
in spotify api call []
I really do not understand why getOldTracks
returns the null trackList
. Why does it keep executing after I specify to await the spotify call? I am not too experienced with asynchronous JS, but I have never had problems like this. I was unable to solve this with promises too, so I am at a loss for why it is executing in incorrect order.