-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync-queue.js
More file actions
55 lines (44 loc) · 1.18 KB
/
async-queue.js
File metadata and controls
55 lines (44 loc) · 1.18 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
46
47
48
49
50
51
52
53
const promise = (name) => {
return new Promise((res) => {
setTimeout(() => {
res(name)
}, Math.round(Math.random() * 5))
});
}
const report = (name) => {
console.log('done', name);
}
const a = promise('a');
const b = promise('b');
const c = promise('c');
const d = promise('d');
class Queue {
constructor(callback) {
if (typeof callback !== 'function')
throw new Error('Queue handler can be only a function');
this.handler = callback;
this.promises = []
this.pendingPromise = null;
}
push(promise) {
if(!(promise instanceof Promise))
throw new Error('Only promise can be pushed to Queue');
this.promises.push(promise)
this.run();
}
run() {
const isCanBeExecuted = !this.pendingPromise;
if(isCanBeExecuted && this.promises.length) {
this.pendingPromise = this.promises.shift().then((res) => {
this.handler(res);
this.pendingPromise = null;
this.run();
})
}
}
}
const queue = new Queue(report);
queue.push(a);
queue.push(b);
queue.push(c);
queue.push(d);