-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
61 lines (55 loc) · 1.4 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
59
60
61
class Queue {
constructor() {
this.queue = [];
this.pendingPromise = false;
}
enqueue = function(promise, onPositionUpdated) {
return new Promise((resolve, reject) => {
this.queue.push({
promise,
resolve,
reject,
onPositionUpdated
});
if(onPositionUpdated) onPositionUpdated(this.workingOnPromise ? this.queue.length : this.queue.length - 1, this.queue.length-1)
this.dequeue();
});
}
dequeue = function() {
this.queue.forEach((queued, idx) => {
if(queued.onPositionUpdated) queued.onPositionUpdated(idx, this.queue.length-1)
});
if (this.workingOnPromise) {
return false;
}
const item = this.queue[0];
if (!item) {
return false;
}
try {
this.workingOnPromise = true;
setTimeout(() => {
item.promise()
.then((value) => {
this.workingOnPromise = false;
item.resolve(value);
this.queue.shift();
this.dequeue();
})
.catch(err => {
this.workingOnPromise = false;
item.reject(err);
this.queue.shift();
this.dequeue();
})
}, 2500)
} catch (err) {
this.workingOnPromise = false;
item.reject(err);
this.queue.shift();
this.dequeue();
}
return true;
}
}
module.exports = Queue