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

107
Visualizações
Need help fixing Javascript execution flow. Console.log is being revalidated upon opening

Alright, I have got the following 3 functions which help me collect Spotify genres based on Artists ID's. Since most tracks on Spotify have multiple Artists, I need to combine all the individual artists genres so that I can use them at a later point.

I have the following 3 functions:

const getArtist = async (artistId) => {
  console.log('4');
  const artistObject = await getData(
    'https://api.spotify.com/v1/artists/' + artistId
  ).then((artistObject) => {
    return artistObject;
  });
};
const getAllGenres = (artists) => {
  let artistGenres = [];
  console.log('2');

  artists.map(async (item) => {
    console.log('3');
    await getArtist(item.id).then(async (artist) => {
      console.log('5');
      await artist.genres.map((genre) => {
        if (artistGenres.indexOf(genre) == -1) {
          artistGenres.push(genre);
        }
      });
    });
  });

  return artistGenres;
};

And

const getGenre = (artists) => {
  console.log('1');
  const allgenres = getAllGenres(artists);

  console.log('6', allgenres);
}

Whenever I check the value of allgenres in the console it looks empty but whenever I click the arrow to unfold it, it has value. I know that this is because it revalidates the value of allgenres whenever I unfold the array.

I have looked online for solutions regarding this and came across async/await. I have tried this and had to change getAllGenres into a promise. Not a problem but it did not solve the issue.

I have added some console.logs to help me understand the current flow of execution:

1
2
3
4
3
4
6 [] <- Revalidates after opening
5
5

From my understanding console.log(6) should be the last to be executed but this is not the case.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As you have been suggested, do not mix then and async/await syntax, since you make the code harder to read, I can't test the code since I don't have access to that api, but this should work:

const getArtist = (artistId) => {
  return getData('https://api.spotify.com/v1/artists/' + artistId);
};

const getAllGenres = async (artists) => {
  let artistGenres = [];
  await Promise.all(
    artists.map(async (item) => {
      const artist = await getArtist(item.id);
      artist.genres.forEach((genre) => {
        if (artistGenres.indexOf(genre) == -1) {
          artistGenres.push(genre);
        }
      });
    })
  );
  return artistGenres;
};

const getGenre = async (artists) => {
  const allgenres = await getAllGenres(artists);
  console.log(allgenres);
};
  1. getArtist doesn't need to be async since getData must be an async function that returns a promise, so getArtist will return a promise automatically.
  2. getGenre on the other hand, must be async, since you need to wat to retrieve all the genres before using them, and that happens asynchronously.
  3. getAllGenres is where you have to be careful, you are going to throw several async calls in parallel, that's a scenario you need to handle with Promise.all, you find a lot of resource here on SO on this specific subject.
about 4 years ago · Juan Pablo Isaza Relatório
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