Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!