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)
}
)