UNPKG

2.78 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.CancellationError = exports.CancellationToken = void 0;
7
8function _events() {
9 const data = require("events");
10
11 _events = function () {
12 return data;
13 };
14
15 return data;
16}
17
18class CancellationToken extends _events().EventEmitter {
19 // babel cannot compile ... correctly for super calls
20 constructor(parent) {
21 super();
22 this.parentCancelHandler = null;
23 this._parent = null;
24 this._cancelled = false;
25
26 if (parent != null) {
27 this.parent = parent;
28 }
29 }
30
31 get cancelled() {
32 return this._cancelled || this._parent != null && this._parent.cancelled;
33 }
34
35 set parent(value) {
36 this.removeParentCancelHandler();
37 this._parent = value;
38
39 this.parentCancelHandler = () => this.cancel();
40
41 this._parent.onCancel(this.parentCancelHandler);
42 }
43
44 cancel() {
45 this._cancelled = true;
46 this.emit("cancel");
47 }
48
49 onCancel(handler) {
50 if (this.cancelled) {
51 handler();
52 } else {
53 this.once("cancel", handler);
54 }
55 }
56
57 createPromise(callback) {
58 if (this.cancelled) {
59 return Promise.reject(new CancellationError());
60 }
61
62 const finallyHandler = () => {
63 if (cancelHandler != null) {
64 try {
65 this.removeListener("cancel", cancelHandler);
66 cancelHandler = null;
67 } catch (ignore) {// ignore
68 }
69 }
70 };
71
72 let cancelHandler = null;
73 return new Promise((resolve, reject) => {
74 let addedCancelHandler = null;
75
76 cancelHandler = () => {
77 try {
78 if (addedCancelHandler != null) {
79 addedCancelHandler();
80 addedCancelHandler = null;
81 }
82 } finally {
83 reject(new CancellationError());
84 }
85 };
86
87 if (this.cancelled) {
88 cancelHandler();
89 return;
90 }
91
92 this.onCancel(cancelHandler);
93 callback(resolve, reject, callback => {
94 addedCancelHandler = callback;
95 });
96 }).then(it => {
97 finallyHandler();
98 return it;
99 }).catch(e => {
100 finallyHandler();
101 throw e;
102 });
103 }
104
105 removeParentCancelHandler() {
106 const parent = this._parent;
107
108 if (parent != null && this.parentCancelHandler != null) {
109 parent.removeListener("cancel", this.parentCancelHandler);
110 this.parentCancelHandler = null;
111 }
112 }
113
114 dispose() {
115 try {
116 this.removeParentCancelHandler();
117 } finally {
118 this.removeAllListeners();
119 this._parent = null;
120 }
121 }
122
123}
124
125exports.CancellationToken = CancellationToken;
126
127class CancellationError extends Error {
128 constructor() {
129 super("Cancelled");
130 }
131
132} exports.CancellationError = CancellationError;
133// __ts-babel@6.0.4
134//# sourceMappingURL=CancellationToken.js.map
\No newline at end of file