-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_queue.js
72 lines (64 loc) · 1.33 KB
/
task_queue.js
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
/**
* A queue to process tasks one at a time
*/
export class TaskQueue {
/** The waiting task to process */
#queue;
/** If a current task is running */
#running;
constructor() {
this.#queue = [];
this.#running = false;
}
/**
* Adds a task to the queue
* @param {Function} task A function to process later
* @throws An Error If the task is not a function
* @returns {void} Nothing
*/
add(task) {
if (!this.#isFunction(task)) {
throw new Error('Task must be a function');
}
this.#queue.push(task);
if (!this.#running) {
this.#execute();
}
}
/** Executes the next task in the queue */
#execute() {
if (this.#queue.length === 0) {
this.#running = false;
return;
}
const task = this.#queue.shift();
this.#running = true;
new Promise((resolve, reject) => {
try {
task()
.then(() => {
resolve();
})
.catch((err) => {
console.error('Task error:', err);
reject(err);
})
.finally(() => {
this.#execute();
});
} catch (error) {
console.error('Task execution error:', error);
reject(error);
this.#execute();
}
});
}
/**
* Checks if the value passed is a function
* @param {Function} fn
* @returns {Boolean} True if the value is a function, false otherwise
*/
#isFunction(fn) {
return typeof fn === 'function';
}
}