Skip to content

Instantly share code, notes, and snippets.

@lukeribchester
Created February 28, 2022 21:38
Show Gist options
  • Save lukeribchester/b8705f6f80cca41c62679a2866fe5cb1 to your computer and use it in GitHub Desktop.
Save lukeribchester/b8705f6f80cca41c62679a2866fe5cb1 to your computer and use it in GitHub Desktop.
class TimedPromise<T> extends Promise<T> {
constructor(
executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: unknown) => void) => void,
ms: number,
onTimeout?: () => void
) {
super((resolve, reject) => {
const timeout = setTimeout(() => {
clearTimeout(timeout);
if (onTimeout) {
onTimeout();
}
reject('Promise has timed out.');
}, ms);
return executor(
(resolve) => { clearTimeout(timeout); return resolve; },
(reject) => { clearTimeout(timeout); return reject; }
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment