asyncTaskManager.js
2.39 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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AsyncTaskManager = void 0;
function _log() {
const data = require("./log");
_log = function () {
return data;
};
return data;
}
function _promise() {
const data = require("./promise");
_promise = function () {
return data;
};
return data;
}
class AsyncTaskManager {
constructor(cancellationToken) {
this.cancellationToken = cancellationToken;
this.tasks = [];
this.errors = [];
}
add(task) {
if (this.cancellationToken == null || !this.cancellationToken.cancelled) {
this.addTask(task());
}
}
addTask(promise) {
if (this.cancellationToken.cancelled) {
_log().log.debug({
reason: "cancelled",
stack: new Error().stack
}, "async task not added");
if ("cancel" in promise) {
promise.cancel();
}
return;
}
this.tasks.push(promise.catch(it => {
_log().log.debug({
error: it.message || it.toString()
}, "async task error");
this.errors.push(it);
return Promise.resolve(null);
}));
}
cancelTasks() {
for (const task of this.tasks) {
if ("cancel" in task) {
task.cancel();
}
}
this.tasks.length = 0;
}
async awaitTasks() {
if (this.cancellationToken.cancelled) {
this.cancelTasks();
return [];
}
const checkErrors = () => {
if (this.errors.length > 0) {
this.cancelTasks();
throwError(this.errors);
return;
}
};
checkErrors();
let result = null;
const tasks = this.tasks;
let list = tasks.slice();
tasks.length = 0;
while (list.length > 0) {
const subResult = await Promise.all(list);
result = result == null ? subResult : result.concat(subResult);
checkErrors();
if (tasks.length === 0) {
break;
} else {
if (this.cancellationToken.cancelled) {
this.cancelTasks();
return [];
}
list = tasks.slice();
tasks.length = 0;
}
}
return result || [];
}
}
exports.AsyncTaskManager = AsyncTaskManager;
function throwError(errors) {
if (errors.length === 1) {
throw errors[0];
} else if (errors.length > 1) {
throw new (_promise().NestedError)(errors, "Cannot cleanup: ");
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=asyncTaskManager.js.map