DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 103

The task is to implement auto-retry when a promise is rejected.

The boilerplate code

function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Keep track of how many retries are happening

return new Promise((resolve, reject) => {

let attempts = 0;
Enter fullscreen mode Exit fullscreen mode

Create a function that calls the function. If the promise is successful, resolve immediately.

const tryFetch = () => {
  fetcher()
  .then(resolve)
  .catch((error) => {
  attempts++;
Enter fullscreen mode Exit fullscreen mode

If it rejects, retry till the maximum retry value is reached

if (attempts > maximumRetryCount) {
            reject(error);
          } else {
            tryFetch();
          }
Enter fullscreen mode Exit fullscreen mode

Call tryFetch once to start the process

tryFetch()
Enter fullscreen mode Exit fullscreen mode

The final code

function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  // your code here
  return new Promise((resolve, reject) => {
    let attempts = 0;

    const tryFetch = () => {
      fetcher()
      .then(resolve)
      .catch((error) => {
        attempts++;

        if(attempts > maximumRetryCount) {
          reject(error);
        } else {
          tryFetch();
        }
      })
    }
    tryFetch();
  })
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)