This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
64. auto-retry Promise on rejection

Here's one possible solution to the coding question:

function fetchWithAutoRetry(fetcher, count) {
  return new Promise((resolve, reject) => {
    function doFetch(attempt) {
      fetcher()
        .then(resolve)
        .catch(() => {
          if (attempt < count) {
            setTimeout(() => doFetch(attempt + 1), 1000);
          } else {
            reject(new Error(`Failed to fetch after ${count} attempts`));
          }
        })
    }
    doFetch(1);
  });
}

The fetchWithAutoRetry function takes two arguments:

  • fetcher: a function that performs the API call and returns a Promise
  • count: the maximum number of times the call can be retried

The function returns a new Promise that resolves with the data returned by the fetcher function, or rejects with an error if the maximum number of retries is reached.

The function works by calling fetcher() inside a doFetch function, which resolves the Promise if the API call succeeds, or retries the call if it fails. The retry logic uses a recursive approach, calling itself with a delay of 1 second until either the call succeeds or the maximum number of retries is reached.

Note that this solution is a simplified version that retries all Promise rejections, including those caused by errors that are not due to network issues. In a real-world scenario, you would need to handle different types of errors and retry only those that are recoverable.