This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathasync-queue.js
82 lines (70 loc) · 1.79 KB
/
async-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
73
74
75
76
77
78
79
80
81
82
class Task {
constructor(fn, parallel = true) {
this.fn = fn;
this.parallel = parallel;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
async execute() {
try {
const value = await this.fn.call(undefined);
this.resolve(value);
} catch (err) {
this.reject(err);
}
}
runsInParallel() {
return this.parallel;
}
runsInSerial() {
return !this.parallel;
}
getPromise() {
return this.promise;
}
}
export default class AsyncQueue {
constructor(options = {}) {
this.parallelism = options.parallelism || 1;
this.nonParallelizableOperation = false;
this.tasksInProgress = 0;
this.queue = [];
}
push(fn, {parallel} = {parallel: true}) {
const task = new Task(fn, parallel);
this.queue.push(task);
this.processQueue();
return task.getPromise();
}
processQueue() {
if (!this.queue.length || this.nonParallelizableOperation || this.disposed) { return; }
const task = this.queue[0];
const canRunParallelOp = task.runsInParallel() && this.tasksInProgress < this.parallelism;
const canRunSerialOp = task.runsInSerial() && this.tasksInProgress === 0;
if (canRunSerialOp || canRunParallelOp) {
this.processTask(task, task.runsInParallel());
this.queue.shift();
this.processQueue();
}
}
async processTask(task, runsInParallel) {
if (this.disposed) { return; }
this.tasksInProgress++;
if (!runsInParallel) {
this.nonParallelizableOperation = true;
}
try {
await task.execute();
} finally {
this.tasksInProgress--;
this.nonParallelizableOperation = false;
this.processQueue();
}
}
dispose() {
this.queue = [];
this.disposed = true;
}
}