Fetch And Retry

PromisesAsync

Implement a retry function that automatically retries a failing async operation a specified number of times.

Function Signature:

function retry(asyncFn, retries = 3, delay = 0)

Examples

Example 1
Input
// Success on first try
retry(() => createMockApi(true, 50), 3, 100)
  .then(result => console.log('Success:', result))
  .catch(error => console.error('Error:', error));
Output
Success: { statusCode: 200, message: 'Success!' }
Explanation
The function succeeds on the first attempt, so it returns immediately without retrying.
Example 2
Input
// Success after retries
let attemptCount = 0;
const succeedOnThirdTry = () => {
  attemptCount++;
  return createMockApi(attemptCount === 3, 50);
};

retry(succeedOnThirdTry, 3, 200)
  .then(result => console.log('Success:', result))
  .catch(error => console.error('Error:', error));
Output
Success: { statusCode: 200, message: 'Success!' }
Explanation
The first two attempts fail, but the third attempt succeeds. The function waits 200ms between each retry.
Example 3
Input
// Failure after all retries
retry(() => createMockApi(false, 50), 3, 100)
  .then(result => console.log('Success:', result))
  .catch(error => console.log('Failed:', error));
Output
Failed: { statusCode: 500, message: 'Internal Server Error on attempt' }
Explanation
All 3 retry attempts fail. The function rejects with the error from the last attempt.

Constraints

  • `asyncFn` is a function that returns a Promise
  • `retries` must be a non-negative integer
  • `delay` must be a non-negative number (milliseconds)
  • If `retries` is 0, the function should only attempt once

Notes

  • Consider using a loop or recursion to implement retries
  • Use `setTimeout` or `Promise` with delay for waiting between retries
  • Handle both resolved and rejected Promises correctly

Hints

Read the full write-up for Fetch And Retry
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it