Created
February 28, 2022 21:38
-
-
Save lukeribchester/b8705f6f80cca41c62679a2866fe5cb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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