DEV Community

jser
jser

Posted on • Edited on

BFE.dev challenge #64 auto-retry Promise on rejection

https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

This article is about the coding problem BFE.dev#64. auto-retry Promise on rejection

Alt Text

Look at the interface

/**
 * @param { () => Promise<any> } fetcher
 * @param { number } maximumRetryCount
 * @returns { Promise<any> }
 */
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode
  1. we need to return a Promise, which calls fetcher
  2. it resolves when fetcher's Promise resolves
  3. goes to 1 when rejection is met

Start coding

First, the fulfilled case is easy.

function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      // to do
    })
  })
}
Enter fullscreen mode Exit fullscreen mode

The triggering of fetcher is a logic that should be run for multiple times, so we wrap it into a named function.

function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    const callFetcher = () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      callFetcher() // when rejected, call it again
    })

    callFetcher()
  })
}
Enter fullscreen mode Exit fullscreen mode

Last, we need to limit the recalling, by comparing with the maximumRetryCount. We could just declare a count variable outside of callFetcher()

function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    let retryCount = 0
    const callFetcher = () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      if (retryCount < maximumRetryCount) {
        callFetcher()
        retryCount += 1
      } else {
        reject(error)
      }
    })

    callFetcher()
  })
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Passed!

Alt Text

This is pretty interesting problem, maybe you can also have a try at https://bfe.dev

Hope it helps, see you next time.

Top comments (0)