Skip to content

Commit

Permalink
add TimeoutError class
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Dec 1, 2024
1 parent 7e38d15 commit d529634
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 20 deletions.
6 changes: 6 additions & 0 deletions src/async/TimeoutError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export class TimeoutError extends Error {
name = 'TimeoutError'
constructor(message?: string) {
super(message ?? 'Operation timed out')
}
}
40 changes: 20 additions & 20 deletions src/async/timeout.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { isString } from 'radashi'
import { isFunction } from 'radashi'
import { TimeoutError } from './TimeoutError'

declare const setTimeout: (fn: () => void, ms: number) => unknown

/**
* Creates a promise that will reject after a specified amount of time.
* You can provide a custom error message or a function that returns an error.
* The `timeout` function creates a promise that rejects after a
* specified delay, with an optional custom error message or error
* function.
*
* @see https://radashi.js.org/reference/async/timeout
*
* @example
* ```ts
* // Reject after 1000 milliseconds with default message "timeout"
Expand All @@ -27,23 +28,22 @@ declare const setTimeout: (fn: () => void, ms: number) => unknown
* ```
* @version 12.3.0
*/

export function timeout<E extends Error>(
milliseconds: number,
export function timeout<TError extends Error>(
/**
* The number of milliseconds to wait before rejecting.
*/
ms: number,
/**
* The error message to reject with.
*
* @default "timeout"
* An error message or a function that returns an error. By default,
* a `TimeoutError` is thrown with the message "Operation timed
* out".
*/
error: string | (() => E) = 'timeout',
): Promise<void> {
return new Promise((_, rej) =>
setTimeout(() => {
if (isString(error)) {
rej(new Error(error))
} else {
rej(error())
}
}, milliseconds),
error?: string | (() => TError),
): Promise<never> {
return new Promise((_, reject) =>
setTimeout(
() => reject(isFunction(error) ? error() : new TimeoutError(error)),
ms,
),
)
}
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export * from './async/reduce.ts'
export * from './async/retry.ts'
export * from './async/sleep.ts'
export * from './async/timeout.ts'
export * from './async/TimeoutError.ts'
export * from './async/tryit.ts'
export * from './async/withResolvers.ts'

Expand Down

0 comments on commit d529634

Please sign in to comment.