[JavaScript]Retry API requests a specified number of times and at a specified time.

Use this implementation when an API request has failed in some way, or when you want to make a subsequent API request after the API request has been made and is OK in process.

目次

Code

If you just want to quickly look at the code, here.

/**
 * API Request
 *
 * 5 retries in a maximum of 2.5 seconds to check HTTP status
 * If 200 is not returned after all retries, null is returned
 */
export async function GetAPIRequest() {
  let retryCount = 0
  const maxRetries = 5

  await new Promise(resolve => setTimeout(resolve, 300))

  while (retryCount < maxRetries) {
    try {
      const response = await fetch(`API request URL`, {
        method: 'GET'
      })

      if (response.status === 200) {
        return await response.json()
      }

      console.log('Retrying...')
    } catch (error) {
      console.error('Error:', error)
    } finally {
      await new Promise(resolve => setTimeout(resolve, 500))
      retryCount++
    }
  }

  return null
}

Explanation

The while and setTimeout are used to control the number of API requests and the execution time.

The while controls the number of retries. In this example, it loops through and exits as many times as the maxRetries variable.

  let retryCount = 0
  const maxRetries = 5

  while (retryCount < maxRetries) {
   ...(API Request)
  retryCount++
  }

Within the while, the API request is described and any processing is executed and checked. In this example, the HTTP status is checked.

If the API side is still processing, it is necessary to wait – setTimeout is used to wait a few seconds before retrieving the data. This depends on the processing speed of the API side, so specify an appropriate value depending on how long it will take and other factors.

In addition, fainally increment the number of retries for all successful and unsuccessful attempts.

try {
  const response = await fetch(`API request URL`, {
    method: 'GET'
  })

  if (response.status === 200) {
    return await response.json()
  }

  console.log('Retrying...')
  await new Promise(resolve => setTimeout(resolve, 500))
} catch (error) {
  console.error('Error:', error)
  await new Promise(resolve => setTimeout(resolve, 500))
} finally {
  retryCount++
}

Summay

The retry process for API requests is coded.

The implementation is simple, but the process needs to be configured depending on how the API requestor is behaving.

よかったらシェアしてね!
目次