-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.ts
More file actions
45 lines (38 loc) · 1.14 KB
/
queue.ts
File metadata and controls
45 lines (38 loc) · 1.14 KB
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
//
// queue.ts - simple task queue used to linearize async operations
//
export type OperationCallback = (error: Error | null) => void
export type Operation = (done: OperationCallback) => void
export class OperationsQueue {
private queue: Operation[] = []
private isProcessing = false
/** Add operations to the queue, process immediately if possible, else wait for previous operations to complete */
public enqueue(operation: Operation): void {
this.queue.push(operation)
if (!this.isProcessing) {
this.processNext()
}
}
/** Clear the queue */
public clear(): void {
this.queue = []
this.isProcessing = false
}
/** Process the next operation in the queue */
private processNext(): void {
if (this.queue.length === 0) {
this.isProcessing = false
return
}
this.isProcessing = true
const operation = this.queue.shift()
operation?.(() => {
// could receive (error) => { ...
// if (error) {
// console.warn('OperationQueue.processNext - error in operation', error)
// }
// process the next operation in the queue
this.processNext()
})
}
}