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