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

313
Visualizações
Calling async function in .map() (React)

I'm trying to iterate over IDs (track.id) and for each of them fetch some data (based on those IDs) from API (getBPM()). I'm pretty sure it's connected with Promises and I'm not very fluent with these yet. Here's the code:

const getBpm = async (id) => {
    const {data} = await axios.get("https://api.spotify.com/v1/audio-features", {
        headers: {
            Authorization: `Bearer ${token}`
        },
        params: {
            ids: id,
        }
    }).catch((error) => {
        console.log(error);
    })
    return Math.round(data[0]?.audio_features[0].tempo);
}

function renderTracks() {
        return tracks?.map((track) => 
            <li key={track.id} className="song-item">
                <a className='link-to-song' href="">
                    <div className="img-with-data">
                    <img src={track.album.images[0].url} alt="" />
                        <div className="title-artist">
                            <p className='song-title'>{track.name}</p>
                            <p className='song-artist'>{track.artists[0].name}</p>
                        </div>
                    </div>
                    <p className="tempo">{getBpm(track.id)}</p>
                </a>
            </li>
        )
}

I've tried some things, but couldn't get it to work. I'd appreciate any kind of help

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

0

When you call an async function you have to await the the function like await getBpm(track.id). Ideally you shouldn't fetch the data in the return statement. the spotify API allows you to fetch multiple tracks on each request. https://developer.spotify.com/console/get-audio-features-several-tracks/ I would do something like

const songIds = tracks.map(track => track.id).join(","); // songIds should be a string of track ID's separated by a comma (if my code errors, you know what to do)
const trackDataFromApi = await getBpm(songIds); // This will give you data for all your songs 

Then you might want to merge your 2 data sets. And add your tempo-data to your tracks-variable.

And your function.

const getBpm = async (ids) => {
    const {data} = await axios.get("https://api.spotify.com/v1/audio-features", {
        headers: {
            Authorization: `Bearer ${token}`
        },
        params: {
            ids: ids, // or just ids for shorthand
        }
    }).catch((error) => {
        console.log(error);
    })
    return data;
}
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