-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathQueue.js
58 lines (48 loc) · 1.16 KB
/
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
import waitUntil from './waitUntil';
class Queue {
pendingEntries = [];
inFlight = 0;
err = null;
constructor(worker, options = {}) {
this.worker = worker;
this.concurrency = options.concurrency || 1;
}
push = (entries) => {
this.pendingEntries = this.pendingEntries.concat(entries);
this.process();
};
process = () => {
const scheduled = this.pendingEntries.splice(0, this.concurrency - this.inFlight);
this.inFlight += scheduled.length;
scheduled.forEach(async (task) => {
try {
await this.worker(task);
} catch (err) {
this.err = err;
} finally {
this.inFlight -= 1;
}
if (this.pendingEntries.length > 0) {
this.process();
}
});
};
wait = (options = {}) =>
waitUntil(
() => {
if (this.err) {
this.pendingEntries = [];
throw this.err;
}
return {
predicate: options.empty
? this.inFlight === 0 && this.pendingEntries.length === 0
: this.concurrency > this.pendingEntries.length,
};
},
{
delay: 50,
},
);
}
export default Queue;