UNPKG

1.32 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3class TimeoutError extends Error {
4 constructor(context) {
5 super();
6 this.context = context;
7 this.name = 'TimeoutError';
8 }
9}
10exports.TimeoutError = TimeoutError;
11class TimeoutPromise {
12 constructor(executor, timeout, context) {
13 this.promise = timeoutPromise(new Promise(executor), timeout, context);
14 }
15 then(onfulfilled, onrejected) {
16 return this.promise.then(onfulfilled, onrejected);
17 }
18 catch(onrejected) {
19 return this.promise.catch(onrejected);
20 }
21 finally(onfinally) {
22 return this.promise.finally(onfinally);
23 }
24}
25exports.TimeoutPromise = TimeoutPromise;
26function timeoutPromise(p, timeout, context) {
27 let timer;
28 const timerPromise = new Promise((resolve, reject) => {
29 if (typeof timeout === 'number') {
30 timer = setTimeout(() => {
31 reject(new TimeoutError(context));
32 }, timeout);
33 }
34 });
35 return Promise.race([p, timerPromise])
36 .then(x => {
37 clearTimeout(timer);
38 return x;
39 })
40 .catch(e => {
41 clearTimeout(timer);
42 return Promise.reject(e);
43 });
44}
45exports.timeoutPromise = timeoutPromise;
46//# sourceMappingURL=timeout-promise.js.map
\No newline at end of file