-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandQueue.js
48 lines (43 loc) · 1.16 KB
/
CommandQueue.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
"use strict";
class CommandQueue {
constructor() {
this.queue = [];
this.queueRunning = false;
this.commands = {};
}
publish(command, data) {
const commandListeners = this.commands[command];
if (commandListeners) {
commandListeners.forEach((listener) =>
this.queue.push({ listener, data })
);
if (!this.queueRunning) {
this.runQueue();
}
}
}
async runQueue() {
this.queueRunning = true;
while (this.queue.length) {
const { listener, data } = this.queue.shift();
try {
// Assuming listener can be an async function
await listener(data);
// Use setImmediate to prevent blocking the event loop
setImmediate(() => this.runQueue());
} catch (error) {
console.error("Error executing listener:", error);
}
return; // Exit after setting the next cycle to prevent synchronous loop
}
this.queueRunning = false;
}
subscribe(command, listener) {
if (!this.commands[command]) {
this.commands[command] = [];
}
this.commands[command].push(listener);
}
}
const queue = new CommandQueue();
module.exports = { queue };