28 lines
618 B
TypeScript
28 lines
618 B
TypeScript
export function promiseTimeout<T>(
|
|
promise: Promise<T>,
|
|
timeoutMs: number,
|
|
): Promise<T | null> {
|
|
let hasPromiseResolved = false;
|
|
|
|
return Promise.race([
|
|
promise.then((value) => {
|
|
hasPromiseResolved = true;
|
|
return value;
|
|
}),
|
|
new Promise((resolve) => setTimeout(resolve, timeoutMs)).then(() => {
|
|
if (hasPromiseResolved) {
|
|
return null;
|
|
}
|
|
|
|
throw new PromiseTimedOutError();
|
|
}),
|
|
]);
|
|
}
|
|
|
|
export class PromiseTimedOutError extends Error {
|
|
constructor(message?: string) {
|
|
super(message ?? "Promise timed out");
|
|
this.name = "PromiseTimedOutError";
|
|
}
|
|
}
|