Function retryFunction

Keeps calling callback until it returns something other than undefined. There is an exponentially-increasing delay between each retry attempt.

If callback throws an exception, the retry is cancelled, bubbling the exception.

// A function that only works some of the time
const flakyFn = async () => {
// do the thing
if (Math.random() > 0.9) return true; // success
return; // fake failure
};

// Retry it up to five times,
// starting with 1000ms interval
const result = await retryFunction(flakyFn, {
limitAttempts: 5
});

if (result.success) {
// Yay
} else {
console.log(`Failed after ${result.attempts} attempts. Elapsed: ${result.elapsed}`);
console.log(result.message);
}

An AbortSignal can be used to cancel process.

const abort = new AbortController();
const result = await retryFunction(cb, { signal: abort.signal });

// Somewhere else...
abort('Cancel!'); // Trigger abort
  • Type Parameters

    • T

    Parameters

    • callback: (() => Promise<undefined | T>)

      Function to run

        • (): Promise<undefined | T>
        • Returns Promise<undefined | T>

    • options: Partial<RetryOpts<T>> = {}

      Options

    Returns Promise<RetryResult<T>>