-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
53 lines (51 loc) · 1.42 KB
/
main.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
/* eslint-disable github/no-then */
const DEFAULT_CONCURRENCY = 1
export const promiseQueue = ({ concurrency = DEFAULT_CONCURRENCY } = { concurrency: DEFAULT_CONCURRENCY }) => {
if (concurrency <= 0) {
throw RangeError('The concurrency value cannot be equal or less than 0')
}
let isEmpty = true
const queue = []
const onFinally = () => {
if (queue.length === 0) {
isEmpty = true
} else {
isEmpty = false
if (concurrency === 1 || queue.length === 1) {
const [callback, onFulfilled, onRejected] = queue.shift()
callback().then(onFulfilled, onRejected).finally(onFinally)
} else {
const slice = queue.splice(0, concurrency)
Promise.allSettled(
slice.map((iterator) => {
return iterator[0]()
})
)
.then((values) => {
// eslint-disable-next-line github/array-foreach
values.forEach((iterator, index) => {
iterator.status === 'fulfilled' ? slice[index][1](iterator.value) : slice[index][2](iterator.reason)
})
})
.finally(onFinally)
}
}
}
const clear = () => {
isEmpty = true
queue.length = 0
}
const push = (callback) => {
return new Promise((onThen, onCatch) => {
queue.push([callback, onThen, onCatch])
if (isEmpty === true) {
onFinally()
}
})
}
return {
clear,
push,
queue,
}
}