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

148
Visualizações
Wait for code to finish executing before moving to next loop iteration

In the following for-loop, I am calling an async function that makes an api call. I want to await that function to make sure I get the necessary data, then push it to an array and only then do I want to move to the next iteration (i++). Right now, it is going through all the i values and finishing the loop and calling the _callback with an empty array.

Loop:

for (let i = 0; i < waypointCityNames.length; i++) {
        const curCityName = waypointCityNames[i]
        await getNameLatLonFromSearch(curCityName, (curWaypointObject) => {
            waypointObjectArray.push(curWaypointObject)
        })
}
_callback(waypointObjectArray)

async api function:

export default async function getNameLatLonFromSearch(cityName, _callback) {
    fetch(BASE_URL + cityName)
        .then((response) => response.json())
        .then((data) => {
            const name = `${data.results[0].locations[0].street} ${data.results[0].locations[0].adminArea5} ${data.results[0].locations[0].adminArea3} ${data.results[0].locations[0].adminArea1}`
            const lat = data.results[0].locations[0].latLng.lat
            const lon = data.results[0].locations[0].latLng.lng
            _callback({
                name: name,
                lat: lat,
                lon: lon,
            })
            return
        })
}

Where its getting called from:

getWaypointLocationObjectArray(
        startLocationName.origin,
        endLocationName.destination,
        leaveTime.leaveHour,
        (waypointsWithTime) => {
//the code is getting to this callback before the  api can finish, so its an empty array
            console.log(waypointsWithTime)
        }
    )
about 4 years ago · Juan Pablo Isaza
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