Skip to content

Instantly share code, notes, and snippets.

@fronterior
Last active February 25, 2022 22:27
Show Gist options
  • Save fronterior/843c3c490c6168e74a1fe0c12c666720 to your computer and use it in GitHub Desktop.
Save fronterior/843c3c490c6168e74a1fe0c12c666720 to your computer and use it in GitHub Desktop.
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