-
Notifications
You must be signed in to change notification settings - Fork 3
/
TaskQueuer.ts
54 lines (44 loc) · 1.43 KB
/
TaskQueuer.ts
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
import { Task, TaskError, TaskErrorHandler } from "./Task";
const defaultTaskErrorHandler = (error: TaskError) => {
console.error("An error occured while running a task in a queuer:", error);
};
export class TaskQueuer {
private queue: Task[];
private isRunningTask: boolean;
private taskErrorHandler: TaskErrorHandler;
constructor(errorHandler?: TaskErrorHandler) {
this.queue = [];
this.isRunningTask = false;
this.taskErrorHandler = errorHandler ?? defaultTaskErrorHandler;
}
add(...tasks: Task[]): void {
this.queue.push(...tasks);
if (!this.isRunningTask) {
(async () => {
await this.runAllTasks();
})();
}
}
clearNextTasks(): void {
this.queue = [];
}
private async runAllTasks(): Promise<void> {
// Immediately save a reference to nextTask to avoid the situation
// where it exists during the test but not within the block
// because an async operation called clearNextTasks()
const nextTask = this.queue.shift();
if (nextTask) {
this.isRunningTask = true;
try {
await nextTask();
}
catch (error) {
this.taskErrorHandler(error);
}
finally {
await this.runAllTasks();
this.isRunningTask = false;
}
}
}
}