Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

86
Visualizações
Asynchronous code is ignoring the calls and running my functions at the same time or even before another function called prior has run. in node.js

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:

  1. Reacting -> skipSong()
  2. skipsong( accesscurrentsong( ))
  3. accesscurrentsong( postNewCurrentSong() )

Despite the function calls being very much in that order the app is running the functions in this order:

  1. accesscurrentsong( postNewCurrentSong() )
  2. skipsong( accesscurrentsong( ))

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.

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda