MCPcopy Create free account
hub / github.com/FlashpointProject/launcher / EventQueue

Class EventQueue

src/back/util/EventQueue.ts:9–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7
8/** Executes a queue of asynchronous functions, one at a time. */
9export class EventQueue implements IEventQueue {
10 /** Max size of queue (Unlimited if undefined) */
11 private readonly maxSize?: number;
12 /** Queue of functions. */
13 private queue: EventFunction[] = [];
14 /** If this is currently executing an event (flag). */
15 private isExecuting = false;
16 /** Called whenever an error occurs. */
17 public onError: (error: any) => void = noop;
18
19 constructor(maxSize?: number) {
20 this.maxSize = maxSize;
21 }
22
23 /**
24 * Add en event to the end of the queue.
25 *
26 * @param event Event function to add.
27 * @param returnPromise If a promise should be returned.
28 * @returns Nothing or a promise that resolves after the event is executed,
29 * or rejects if it rejects or throws an error.
30 */
31 push(event: EventFunction, returnPromise?: boolean): Promise<void> | void {
32 // Wrap the event, and create a promise, if a promise should be returned
33 const [wrappedEvent, promise] = returnPromise ? wrapEvent(event) : [undefined, undefined];
34 // Push end off early if max size is reached
35 if (this.queue.length === this.maxSize) {
36 this.queue.shift();
37 }
38 // Add event to the end of the queue
39 this.queue.push(wrappedEvent || event);
40 this.update();
41 // Return promise (if any)
42 return promise;
43 }
44
45 private update() {
46 if (!this.isExecuting && this.queue.length > 0) {
47 // Update flag
48 this.isExecuting = true;
49 // Start executing
50 this.executeNext()
51 .finally(() => { this.isExecuting = false; });
52 }
53 }
54
55 /**
56 * Execute the next event in the queue (and continue doing so until the queue is empty).
57 *
58 * @returns A promise that resolves when it reaches the end of the queue.
59 */
60 private async executeNext(): Promise<void> {
61 const event = this.queue.shift();
62 if (event) {
63 try { await executeEventFunction(event); }
64 catch (error) { this.onError(error); }
65 await this.executeNext();
66 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected