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
Look at the interface
/**
* @param { () => Promise<any> } fetcher
* @param { number } maximumRetryCount
* @returns { Promise<any> }
*/
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
// your code here
}
- we need to return a Promise, which calls fetcher
- it resolves when fetcher's Promise resolves
- 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
})
})
}
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()
})
}
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()
})
}
That's it!
Passed!
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)