2023-01-03 10:47:44 +00:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2022-03-01 04:25:50 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
2021-07-12 12:44:57 +00:00
|
|
|
import { deferred } from "./deferred.ts";
|
|
|
|
|
|
|
|
export class DeadlineError extends Error {
|
|
|
|
constructor() {
|
|
|
|
super("Deadline");
|
|
|
|
this.name = "DeadlineError";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Create a promise which will be rejected with {@linkcode DeadlineError} when a given delay is exceeded.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```typescript
|
|
|
|
* import { deadline } from "https://deno.land/std@$STD_VERSION/async/deadline.ts";
|
|
|
|
* import { delay } from "https://deno.land/std@$STD_VERSION/async/delay.ts";
|
|
|
|
*
|
|
|
|
* const delayedPromise = delay(1000);
|
|
|
|
* // Below throws `DeadlineError` after 10 ms
|
|
|
|
* const result = await deadline(delayedPromise, 10);
|
|
|
|
* ```
|
2021-07-12 12:44:57 +00:00
|
|
|
*/
|
|
|
|
export function deadline<T>(p: Promise<T>, delay: number): Promise<T> {
|
|
|
|
const d = deferred<never>();
|
|
|
|
const t = setTimeout(() => d.reject(new DeadlineError()), delay);
|
2021-08-07 08:13:25 +00:00
|
|
|
return Promise.race([p, d]).finally(() => clearTimeout(t));
|
2021-07-12 12:44:57 +00:00
|
|
|
}
|