-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
43 lines (40 loc) · 857 Bytes
/
index.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
var delay = (seconds) =>
new Promise((resolves) => {
setTimeout(resolves, seconds * 1000);
});
var tasks = [
delay(4),
delay(6),
delay(4),
delay(3),
delay(5),
delay(7),
delay(9),
delay(10),
delay(3),
delay(5),
];
class PromiseQueue {
constructor(promises = [], concurrentCount = 1) {
this.concurrent = concurrentCount;
this.total = promises.length;
this.todo = promises;
this.running = [];
this.complete = [];
}
get runAnother() {
return this.running.length < this.concurrent && this.todo.length;
}
run() {
while (this.runAnother) {
var promise = this.todo.shift();
promise.then(() => {
this.complete.push(this.running.shift());
this.run();
});
this.running.push(promise);
}
}
}
var delayQueue = new PromiseQueue(tasks, 2);
delayQueue.run();