DEV Community

Discussion on: Javascript fetch, retry upon failure.

Collapse
 
norfeldtabtion profile image
Lasse Norfeldt • Edited

I gave it a swing with deno and came up with this:

fetchWithRetry.ts

type Parameters = {
  url: string
  numberOfRetries?: number
  print?: boolean
  dev?: boolean
}

export async function fetchWithRetry({
  url,
  numberOfRetries = 3,
  print,
  dev,
}: Parameters): Promise<Response> {
  const retriesLeft = numberOfRetries - 1
  print && console.log(`Retries left: ${retriesLeft}, url: ${url}`)

  if (retriesLeft == 0) return Promise.reject('Too many attemps without luck')

  return await fetch(url).catch(async (error) => {
    if (numberOfRetries !== 0) {
      await fetchWithRetry({
        url: !dev ? url : url.slice(0, -1),
        numberOfRetries: retriesLeft,
        print,
        dev,
      })
    }
    return error
  })
}

if (import.meta.main) {
  console.log('main')

  const successUrl = 'https://www.google.com'
  const failureUrl = 'https://www.googsdsdsdsdle.com'
  const partialFailingUrl = 'https://www.google.com1'

  console.log(successUrl)
  await fetchWithRetry({ url: successUrl, print: true })

  console.log(failureUrl)
  await fetchWithRetry({ url: failureUrl, print: true }).catch(() => {})

  console.log(partialFailingUrl)
  await fetchWithRetry({ url: partialFailingUrl, print: true, dev: true })
}

Enter fullscreen mode Exit fullscreen mode
deno run --allow-net fetchWithRetry.ts
Enter fullscreen mode Exit fullscreen mode

The short version of it

type Parameters = {
  url: string
  numberOfRetries?: number
}

export async function fetchWithRetry({
  url,
  numberOfRetries = 3
}: Parameters): Promise<Response> {
  const retriesLeft = numberOfRetries - 1
  if (retriesLeft == 0) return Promise.reject('Too many attemps without luck')

  return await fetch(url).catch(async (error) => {
    if (numberOfRetries !== 0) {
      await fetchWithRetry({
        url,
        numberOfRetries: retriesLeft,
      })
    }
    return error
  })
}
Enter fullscreen mode Exit fullscreen mode