0

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)
        })
    }
})()
Aaron Jan
  • 58
  • 6
  • It is not possible that `setTimeout` is called before `convertToAddress`. Your `run` function will execute `convertToAddress` and return a promise. – trincot Dec 17 '20 at 19:07
  • Does `covertToAddresses` return a promise which you can `await`? – Bergi Dec 17 '20 at 19:13
  • The console log in `timeout` sometimes prints before or sometimes multiple times after the console log that is inside `convertToAddress`. – Aaron Jan Dec 17 '20 at 19:15
  • @Bergi, yes convertToAddresses does return a promise that I'm awaiting which works fine without the timeout fxn – Aaron Jan Dec 17 '20 at 19:17
  • I've tried invoking `timeout` inside the .then of convertToAddresses, but I still get the same behavior – Aaron Jan Dec 17 '20 at 19:19
  • @AaronJan But then `covertToAddresses` is broken if it prints a console log *after* fulfilling the returned promise. Please [edit] your question to include that code – Bergi Dec 17 '20 at 19:19
  • Replace `convertToAddress` with a `console.log`. I'm betting that your issue is in `convertToAddress`, not `timeout`. Also you don't need to await the Promise inside of the `timeout` if you're awaiting in `run`. Just return the Promise in `timeout`. – Kevin Aung Dec 17 '20 at 19:19
  • @trincot I don't think https://stackoverflow.com/questions/40328932/javascript-es6-promise-for-loop solves the OP's problem. Maybe https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop, but it seems there's something else at play here (it rather should be closed for lacking debugging info). – Bergi Dec 17 '20 at 19:22
  • https://gist.github.com/kkaung/645c812891c09062a8621a3efbb9365a – Kevin Aung Dec 17 '20 at 19:28
  • I implemented your solution @KevinAung; and message got console logged several times before the log in `convertToAddresses` like before. So perhaps the problem is in `convertToAddresses`, which I've edited the Q to include @Bergi – Aaron Jan Dec 17 '20 at 19:34
  • replacing `convertToAddresses` with a console log does produce console logs in the correct order. So I'll look into this fxn to fix the problem. Thanks @Bergi – Aaron Jan Dec 17 '20 at 19:39
  • @AaronJan The `convertToAddresses` looks fine (although the `.then` syntax should be replaced by `await`). Are you really saying the `console.log('count', count);` occurs after the `console.log('waiting for 10 seconds')`? – Bergi Dec 17 '20 at 21:30
  • this is exactly what I get: – Aaron Jan Dec 17 '20 at 21:34
  • ``` waiting for 10 seconds \ waiting for 10 seconds \ waiting for 10 seconds \ waiting for 10 seconds \ waiting for 10 seconds \ waiting for 10 seconds \ count 1 \ waiting for 10 seconds \ count 2 \ waiting for 10 seconds .... ``` – Aaron Jan Dec 17 '20 at 21:34

0 Answers0