-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromiseQueue.js
More file actions
63 lines (57 loc) · 1.49 KB
/
Copy pathPromiseQueue.js
File metadata and controls
63 lines (57 loc) · 1.49 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
54
55
56
57
58
59
60
61
62
63
/**
* Author and copyright: Stefan Haack (https://shaack.com)
* Repository: https://github.com/shaack/cm-web-modules
* License: MIT, see file 'LICENSE'
*
* Thanks to markosyan
* https://medium.com/@karenmarkosyan/how-to-manage-promises-into-dynamic-queue-with-vanilla-javascript-9d0d1f8d4df5
*/
export class PromiseQueue {
constructor() {
this.queue = []
this.workingOnPromise = false
this.stop = false
}
async enqueue(promise) {
return new Promise((resolve, reject) => {
this.queue.push({
promise, resolve, reject,
})
this.dequeue()
})
}
dequeue() {
if (this.workingOnPromise) {
return
}
if (this.stop) {
this.queue = []
this.stop = false
return
}
const entry = this.queue.shift()
if (!entry) {
return
}
try {
this.workingOnPromise = true
entry.promise().then((value) => {
this.workingOnPromise = false
entry.resolve(value)
this.dequeue()
}).catch(err => {
this.workingOnPromise = false
entry.reject(err)
this.dequeue()
})
} catch (err) {
this.workingOnPromise = false
entry.reject(err)
this.dequeue()
}
return true
}
destroy() {
this.stop = true
}
}