diff --git a/src/retry.ts b/src/retry.ts index 26dd3c2..7f30ec8 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -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 = [Error, null] | [null, T]; + /** * Retries a promise-returning function a specified number of times with an optional delay between attempts if it fails. * @@ -19,8 +27,7 @@ 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} The resolved value of the promise. - * @throws {Error} Throws an error if all retry attempts fail. + * @returns {Promise>} A promise that resolves to a tuple containing either an error or a value, and the duration in milliseconds. * * @includeExample examples/retry.ts */ @@ -28,14 +35,14 @@ export async function retry( fn: () => Promise, attempts: number, options?: RetryOptions -): Promise { +): Promise> { // 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 @@ -45,7 +52,7 @@ export async function retry( // 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 @@ -54,7 +61,7 @@ export async function retry( 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 @@ -65,5 +72,5 @@ export async function retry( } // If all attempts fail, throw the last encountered error - throw lastError; + return [lastError, null]; }