2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-06-21 06:37:23 +00:00
|
|
|
// TODO(iuioiua): Add web-compatible declaration once TypeScript 5.5 is released
|
|
|
|
// and in the Deno runtime. See https://github.com/microsoft/TypeScript/pull/58211
|
|
|
|
//
|
|
|
|
// Note: this code is still compatible with recent
|
|
|
|
// web browsers. See https://caniuse.com/?search=AbortSignal.any
|
|
|
|
import { abortable } from "./abortable.ts";
|
2023-05-02 06:04:26 +00:00
|
|
|
|
2024-05-22 00:40:43 +00:00
|
|
|
/** Options for {@linkcode deadline}. */
|
2023-05-02 06:04:26 +00:00
|
|
|
export interface DeadlineOptions {
|
|
|
|
/** Signal used to abort the deadline. */
|
|
|
|
signal?: AbortSignal;
|
|
|
|
}
|
2021-07-12 12:44:57 +00:00
|
|
|
|
2024-05-22 00:40:43 +00:00
|
|
|
/**
|
2024-06-21 06:37:23 +00:00
|
|
|
* Create a promise which will be rejected with {@linkcode DOMException} when
|
2023-12-01 02:19:22 +00:00
|
|
|
* a given delay is exceeded.
|
2022-11-25 11:40:23 +00:00
|
|
|
*
|
2023-12-01 02:19:22 +00:00
|
|
|
* Note: Prefer to use {@linkcode AbortSignal.timeout} instead for the APIs
|
|
|
|
* that accept {@linkcode AbortSignal}.
|
2023-02-03 03:30:37 +00:00
|
|
|
*
|
2024-06-21 06:37:23 +00:00
|
|
|
* @throws {DOMException} When the provided duration runs out before resolving
|
|
|
|
* or if the optional signal is aborted, and `signal.reason` is undefined.
|
2024-05-22 00:40:43 +00:00
|
|
|
* @typeParam T The type of the provided and returned promise.
|
|
|
|
* @param p The promise to make rejectable.
|
|
|
|
* @param ms Duration in milliseconds for when the promise should time out.
|
|
|
|
* @param options Additional options.
|
|
|
|
* @returns A promise that will reject if the provided duration runs out before resolving.
|
|
|
|
*
|
2024-05-22 05:08:36 +00:00
|
|
|
* @example Usage
|
2024-05-22 00:40:43 +00:00
|
|
|
* ```ts no-eval
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { deadline } from "@std/async/deadline";
|
|
|
|
* import { delay } from "@std/async/delay";
|
2022-11-25 11:40:23 +00:00
|
|
|
*
|
2024-06-21 06:37:23 +00:00
|
|
|
* const delayedPromise = delay(1_000);
|
|
|
|
* // Below throws `DOMException` after 10 ms
|
2022-11-25 11:40:23 +00:00
|
|
|
* const result = await deadline(delayedPromise, 10);
|
|
|
|
* ```
|
2021-07-12 12:44:57 +00:00
|
|
|
*/
|
2024-06-21 06:37:23 +00:00
|
|
|
export async function deadline<T>(
|
2023-05-02 06:04:26 +00:00
|
|
|
p: Promise<T>,
|
|
|
|
ms: number,
|
|
|
|
options: DeadlineOptions = {},
|
|
|
|
): Promise<T> {
|
2024-06-21 06:37:23 +00:00
|
|
|
const signals = [AbortSignal.timeout(ms)];
|
|
|
|
if (options.signal) signals.push(options.signal);
|
|
|
|
return await abortable(p, AbortSignal.any(signals));
|
2021-07-12 12:44:57 +00:00
|
|
|
}
|