Here's a while loop that calls Google's geocode API every iteration. I want to slow down the frequency that the API is called by waiting 5-10 seconds before the while loop repeats again. Because setTimeout is asynchronous, I have it being resolved as a promise so that I can await for timeout
, but the behavior I get is that setTimeout
executes even before covertToAddresses
fxn is called. What I've also tried is converting the while loop into setInterval
which had the consequence of ignoring await altogether. I would really like to understand why this implementation doesn't work.
async function convertToAddress() {
await axios.get(reverseGeoCodeURL).then(res => {
let ranAddr = res.data.results[0].formatted_address
let corrCity = new RegExp(`, ${city},`, 'i');
// before adding the address to an array to be added
// make sure it's a Soutlake address
if (corrCity.exec(ranAddr)) {
transPredtoJSON(ranAddr)
count += 1
console.log('count', count);
}
}).catch(error => {
console.error('error: ', error);
})
}
function timeout() {
return new Promise(resolve => setTimeout(resolve('waiting for 10 seconds'), 10000));
(async function run() {
while (count < enoughAddresses) {
randomCoordinate = randomGeo({ latitude: originlat, longitude: originlng }, radius)
lat = randomCoordinate.latitude
lng = randomCoordinate.longitude
reverseGeoCodeURL = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${result.parsed.GEOCODE_API_KEY}
await convertToAddress(reverseGeoCodeURL)
await timeout().then(res => {
console.log(res)
})
}
})()