1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.AsyncTaskManager = void 0;
|
7 |
|
8 | function _log() {
|
9 | const data = require("./log");
|
10 |
|
11 | _log = function () {
|
12 | return data;
|
13 | };
|
14 |
|
15 | return data;
|
16 | }
|
17 |
|
18 | function _promise() {
|
19 | const data = require("./promise");
|
20 |
|
21 | _promise = function () {
|
22 | return data;
|
23 | };
|
24 |
|
25 | return data;
|
26 | }
|
27 |
|
28 | class AsyncTaskManager {
|
29 | constructor(cancellationToken) {
|
30 | this.cancellationToken = cancellationToken;
|
31 | this.tasks = [];
|
32 | this.errors = [];
|
33 | }
|
34 |
|
35 | add(task) {
|
36 | if (this.cancellationToken == null || !this.cancellationToken.cancelled) {
|
37 | this.addTask(task());
|
38 | }
|
39 | }
|
40 |
|
41 | addTask(promise) {
|
42 | if (this.cancellationToken.cancelled) {
|
43 | _log().log.debug({
|
44 | reason: "cancelled",
|
45 | stack: new Error().stack
|
46 | }, "async task not added");
|
47 |
|
48 | if ("cancel" in promise) {
|
49 | promise.cancel();
|
50 | }
|
51 |
|
52 | return;
|
53 | }
|
54 |
|
55 | this.tasks.push(promise.catch(it => {
|
56 | _log().log.debug({
|
57 | error: it.message || it.toString()
|
58 | }, "async task error");
|
59 |
|
60 | this.errors.push(it);
|
61 | return Promise.resolve(null);
|
62 | }));
|
63 | }
|
64 |
|
65 | cancelTasks() {
|
66 | for (const task of this.tasks) {
|
67 | if ("cancel" in task) {
|
68 | task.cancel();
|
69 | }
|
70 | }
|
71 |
|
72 | this.tasks.length = 0;
|
73 | }
|
74 |
|
75 | async awaitTasks() {
|
76 | if (this.cancellationToken.cancelled) {
|
77 | this.cancelTasks();
|
78 | return [];
|
79 | }
|
80 |
|
81 | const checkErrors = () => {
|
82 | if (this.errors.length > 0) {
|
83 | this.cancelTasks();
|
84 | throwError(this.errors);
|
85 | return;
|
86 | }
|
87 | };
|
88 |
|
89 | checkErrors();
|
90 | let result = null;
|
91 | const tasks = this.tasks;
|
92 | let list = tasks.slice();
|
93 | tasks.length = 0;
|
94 |
|
95 | while (list.length > 0) {
|
96 | const subResult = await Promise.all(list);
|
97 | result = result == null ? subResult : result.concat(subResult);
|
98 | checkErrors();
|
99 |
|
100 | if (tasks.length === 0) {
|
101 | break;
|
102 | } else {
|
103 | if (this.cancellationToken.cancelled) {
|
104 | this.cancelTasks();
|
105 | return [];
|
106 | }
|
107 |
|
108 | list = tasks.slice();
|
109 | tasks.length = 0;
|
110 | }
|
111 | }
|
112 |
|
113 | return result || [];
|
114 | }
|
115 |
|
116 | }
|
117 |
|
118 | exports.AsyncTaskManager = AsyncTaskManager;
|
119 |
|
120 | function throwError(errors) {
|
121 | if (errors.length === 1) {
|
122 | throw errors[0];
|
123 | } else if (errors.length > 1) {
|
124 | throw new (_promise().NestedError)(errors, "Cannot cleanup: ");
|
125 | }
|
126 | }
|
127 |
|
128 |
|
\ | No newline at end of file |