Skip to content

retry

Retries a promise-returning function up to maxAttempts times

Available since v1.9.0

import { retry } from '@helpers4/promise';
retry<T>(fn: function, maxAttempts: number, delayMs: number): Promise<T>
ParameterTypeDescription
fnfunctionThe function to retry
maxAttemptsnumberMaximum number of attempts
delayMsnumberDelay between attempts in milliseconds

Promise<T> — Promise that resolves with the result or rejects with the last error

Retries the function up to maxAttempts times before giving up.

let attempt = 0;
await retry(() => {
  attempt++;
  if (attempt < 3) throw new Error('not yet');
  return Promise.resolve('success');
}, 3, 10)
// => 'success' (after 2 failures)

View source on GitHub