mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
19 lines
509 B
TypeScript
19 lines
509 B
TypeScript
|
import { deferred } from "./deferred.ts";
|
||
|
|
||
|
export class DeadlineError extends Error {
|
||
|
constructor() {
|
||
|
super("Deadline");
|
||
|
this.name = "DeadlineError";
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Create a promise which will be rejected with DeadlineError when a given delay is exceeded.
|
||
|
*/
|
||
|
export function deadline<T>(p: Promise<T>, delay: number): Promise<T> {
|
||
|
const d = deferred<never>();
|
||
|
const t = setTimeout(() => d.reject(new DeadlineError()), delay);
|
||
|
p.finally(() => clearTimeout(t));
|
||
|
return Promise.race([p, d]);
|
||
|
}
|