@beenotung/tslib
Version:
utils library in Typescript
50 lines (49 loc) • 1.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeoutPromise = exports.TimeoutError = void 0;
exports.timeoutPromise = timeoutPromise;
class TimeoutError extends Error {
context;
constructor(context) {
super();
this.context = context;
this.name = 'TimeoutError';
}
}
exports.TimeoutError = TimeoutError;
class TimeoutPromise {
[Symbol.toStringTag];
promise;
constructor(executor, timeout, context) {
this.promise = timeoutPromise(new Promise(executor), timeout, context);
}
then(onfulfilled, onrejected) {
return this.promise.then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.promise.catch(onrejected);
}
finally(onfinally) {
return this.promise.finally(onfinally);
}
}
exports.TimeoutPromise = TimeoutPromise;
function timeoutPromise(p, timeout, context) {
let timer;
const timerPromise = new Promise((resolve, reject) => {
if (typeof timeout === 'number') {
timer = setTimeout(() => {
reject(new TimeoutError(context));
}, timeout);
}
});
return Promise.race([p, timerPromise])
.then(x => {
clearTimeout(timer);
return x;
})
.catch(e => {
clearTimeout(timer);
return Promise.reject(e);
});
}