UNPKG

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