Skip to content

Commit

Permalink
refactor: used to in retry
Browse files Browse the repository at this point in the history
Changelog: refactor
  • Loading branch information
mrspartak committed Jun 22, 2024
1 parent 041d305 commit 72a97a1
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ type RetryOptions = {
delay?: number;
};

/**
* Type representing the output of the retry function.
* The result is a tuple that includes either an error or a value, and the duration in milliseconds.
*
* @template T The type of the resolved value of the promise.
*/
type RetryOut<T> = [Error, null] | [null, T];

/**
* Retries a promise-returning function a specified number of times with an optional delay between attempts if it fails.
*
Expand All @@ -19,23 +27,22 @@ type RetryOptions = {
* @param {number} attempts - The number of retry attempts. Must be a positive integer.
* @param {RetryOptions} [options] - Optional settings for retry behavior.
* @param {number} [options.delay=0] - The delay (in milliseconds) between retry attempts.
* @returns {Promise<T>} The resolved value of the promise.
* @throws {Error} Throws an error if all retry attempts fail.
* @returns {Promise<RetryOut<T>>} A promise that resolves to a tuple containing either an error or a value, and the duration in milliseconds.
*
* @includeExample examples/retry.ts
*/
export async function retry<T>(
fn: () => Promise<T>,
attempts: number,
options?: RetryOptions
): Promise<T> {
): Promise<RetryOut<T>> {
// Ensure the number of attempts is greater than 0
if (attempts < 1) {
throw new Error("attempts must be greater than 0");
return [new Error("retry: attempts must be greater than 0"), null];
}
// Ensure the number of attempts is an integer
if (attempts % 1 !== 0) {
throw new Error("attempts must be an integer");
return [new Error("retry: attempts must be a positive integer"), null];
}

let lastError!: Error; // Placeholder for the last encountered error
Expand All @@ -45,7 +52,7 @@ export async function retry<T>(

// Ensure the delay amount is non-negative
if (delayAmount < 0) {
throw new Error("delay must be greater than or equal to 0");
return [new Error("retry: delay must be non-negative"), null];
}

// Loop to retry the function the specified number of times
Expand All @@ -54,7 +61,7 @@ export async function retry<T>(
const [error, result] = await to(fn());
// If no error, return the result
if (!error) {
return result;
return [null, result];
}

// If there's a delay, wait for the specified amount of time before the next attempt
Expand All @@ -65,5 +72,5 @@ export async function retry<T>(
}

// If all attempts fail, throw the last encountered error
throw lastError;
return [lastError, null];
}

0 comments on commit 72a97a1

Please sign in to comment.