Loading problem…
The promiseRetry function retries an asynchronous operation until it succeeds or the attempt limit is reached.
Implement promiseRetry(fn, options) where fn is a function that returns a Promise. If the promise rejects, retry it up to maxRetries total attempts.
The delay should follow exponential backoff:
delay = initialDelay * (backoffMultiplier ^ attempt)
If all attempts fail, reject with the last error. If any attempt succeeds, resolve with its result.
{
maxRetries: 3, // total number of attempts (including the first)
initialDelay: 100,
backoffMultiplier: 2
}let attempts = 0;
const fn = () => {
attempts++;
return attempts < 2
? Promise.reject('fail-' + attempts)
: Promise.resolve('ok');
};
promiseRetry(fn, { maxRetries: 2, initialDelay: 10 })
.catch(console.log); // 'fail-2'