Home > database >  Create a loop that calls an API and retries 3 times if it errors
Create a loop that calls an API and retries 3 times if it errors

Time:09-08

So just like the title says im trying to create a javascript loop that calls an API, if there is data returned it sets the let variable and jumps out the loop but if it errors it retries 3 times. I did some googling and came up with the following but its not working and i cant understand why?

  let data
  const maxTries = 3

  for (let i = 0; i <= maxTries; i  ) {
    try {
      data = await getJson(url, true)
      if (data) {
        return data
      }
    } catch (err) {
      console.error(err)
      throw err
    }
  }

CodePudding user response:

throw will stop everything. You probably want to do console.error only.

CodePudding user response:

const maxRetries  = 3
    async fetchAndRetryOnError(url, requestOption, maxRetries = 3) {
        let response = await fetch(url, requestOption);
        let retries = 0
        while (!response.ok && response.status != 400 && retries < maxRetries) {
            console.log(response.status);
            await sleep(1000   1000 * 2 ** retries)
            retries  = 1
            response = await fetch(url, requestOption);
            console.log(`Retry nr. ${retries} result: ${response.ok}`)
        }
        return response
    }

    async send() {
        let url = `your url`;
        let requestOption = "" // header or body of req.
        return await this.fetchAndRetryOnError(url, requestOption);
    }

  • Related