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?

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

Leave a Reply