I am creating a slack bot that accesses Spotify API to do things such as play songs, queue songs, skip songs, and report the currently playing track.
The problem is when trying to skip a song and then access the new current song and lastly report it to the slack chat. the function calls are as follows:
Despite the function calls being very much in that order the app is running the functions in this order:
as you can probably tell this ends up posting the song that was skipped and then skipping the song. Does anyone have any idea how I can best make this synchronous?
Thank you.
reaction listener:
app.event("reaction_added", async ({ event }) => {
console.log(event);
const reaction = event.reaction;
if (reaction === "hankey") {
skipSong();
}
});
Access current song:
const accessCurrentSong = (token) => {
const options = {
url: "https://api.spotify.com/v1/me/player",
headers: { Authorization: `Bearer ${token}` },
json: true,
};
try{
request.get(options, function (error, response, body) {
if (error) {
console.error(error);
} else {
const { name, artists, duration_ms, album } = body.item;
SONG = name;
ARTISTS = getArtists(artists);
DURATION = convertDuration(duration_ms);
IMAGE_URL = album.images[0].url;
RELEASE_DATE = album.release_date;
DEVICE_ID = body.device.id;
console.log(
`Song Title: ${SONG} \nArtist: ${ARTISTS} \n${DURATION}
\n ${IMAGE_URL} \n ${DEVICE_ID}`
);
postCurrentSong(SONG, ARTISTS, DURATION, IMAGE_URL,
RELEASE_DATE)
}
});
} catch {
refreshToken();
accessCurrentSong(ACCESS_TOKEN)
}
}
skip current song:
const skipSong = () => {
const skipOptions = {
url: `https://api.spotify.com/v1/me/player/next?
device_id=${DEVICE_ID}`,
headers: { Authorization: `Bearer ${ACCESS_TOKEN}` },
json: true,
};
request.post(skipOptions, function (err, response) {
if (err) console.log("error occurred");
else console.log(`song skipped\n ${response}`);
});
accessCurrentSong(ACCESS_TOKEN)
};
I have some console.log for testing in each function and they're being logged seemingly at the same time. even though access current song isn't called until the end of the skip function the access current song test is logged after the first skip test log and before the last skip output.