The task is to implement auto-retry when a promise is rejected.
The boilerplate code
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
// your code here
}
Keep track of how many retries are happening
return new Promise((resolve, reject) => {
let attempts = 0;
Create a function that calls the function. If the promise is successful, resolve immediately.
const tryFetch = () => {
fetcher()
.then(resolve)
.catch((error) => {
attempts++;
If it rejects, retry till the maximum retry value is reached
if (attempts > maximumRetryCount) {
reject(error);
} else {
tryFetch();
}
Call tryFetch once to start the process
tryFetch()
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();
})
}
That's all folks!
Top comments (0)