Last active
February 25, 2022 22:27
-
-
Save fronterior/843c3c490c6168e74a1fe0c12c666720 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 TPromise<T> extends Promise<T> { | |
static TimeoutError = class extends Error {}; | |
constructor( | |
f: ( | |
resolve: (value: T | PromiseLike<T>) => void, | |
reject: (reason?: any) => void | |
) => void, | |
timeout: number = Infinity | |
) { | |
let resolve, reject; | |
super((res, rej) => { | |
resolve = res; | |
reject = rej; | |
}); | |
const timer = | |
timeout === Infinity | |
? null | |
: setTimeout(() => { | |
reject( | |
new TPromise.TimeoutError(`Load timeout for promise: ${timeout}`) | |
); | |
}, timeout); | |
f( | |
(val: T | PromiseLike<T>) => { | |
resolve(val); | |
clearTimeout(timer); | |
}, | |
(err) => { | |
reject(err); | |
clearTimeout(timer); | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment