From 6f73991588c4fe3e4bafa8a6b5e0e867311df190 Mon Sep 17 00:00:00 2001 From: rjawesome Date: Tue, 25 Jun 2024 14:38:27 -0700 Subject: [PATCH] create timeout promise function --- src/misc.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/misc.ts b/src/misc.ts index bd41f14..08b1a1a 100644 --- a/src/misc.ts +++ b/src/misc.ts @@ -49,3 +49,27 @@ export function cartesian(a: number[][]): number[][] { } return o; } + +export class TimeoutError extends Error { + constructor(message: string) { + super(message); + this.name = "TimeoutError"; + } +} + +// Do not use on the same promise multiple times +export function timeoutPromise(promise: Promise, timeout: number): Promise { + let reject = (_: any) => {}; + let resolve = (_: T) => {}; + const cancel = setTimeout(() => { + reject(new TimeoutError(`Promise exceeded timeout of ${timeout/1000} seconds.`)); + }, timeout); + promise + .then(result => resolve(result)) + .catch(error => reject(error)) + .finally(() => clearTimeout(cancel)); + return new Promise((newResolve, newReject) => { + resolve = newResolve; + reject = newReject; + }); +} \ No newline at end of file