Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

recursive function in javascript to avoid too many requests error not working

I’m getting a list of people from an api, then needs to loop through that list to get their image from a different api. The server where the images live has rate limiting in place, so I’m running into 429 errors (too many requests). I’m trying to delay each call to the server to avoid this issue. But I can’t get me code to work. After the error, the function runs again, but doesn’t return the image.

Here is the function:

async function getImage(id) {
    console.log('getImage function is running')
        const response = await fetch('/some/api/' + id)

        if(response.ok) {
            return await response.text()
        } else {
            setTimeout(async () => {
                return await getImage(id)
            }, 2000)
        }
    }

If the function doesn’t encouter the 429 error, it returns the image string as needed, but if it hits the error, it re-runs, but then does nothing. What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried creating a recursive function, thinking that if the function encounters the error, it will just try again every 2 seconds, until it succeeds. Instead, it just dies.

>Solution :

Wrap setTimeout in a Promise so that you can await it.

await new Promise(r => setTimeout(r, 2000));
return await getImage(id);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading