-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskQueue.js
101 lines (85 loc) · 2.17 KB
/
TaskQueue.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
export class TaskQueue {
#concurrency = 1
#resolveQueueEmpty = null
#queueEmptyPromise = null
#queue = []
#concurrentTaskCount = 0
constructor( concurrency ) {
this.#concurrency = concurrency || this.#concurrency
}
get concurrency() {
return this.#concurrency
}
get concurrentTaskCount() {
return this.#concurrentTaskCount
}
get finished() {
if ( !this.queue.length && this.#concurrentTaskCount === 0 ) {
return Promise.resolve( true )
}
// Return queueEmptyPromise, creating a new one if necessary.
return this.#queueEmptyPromise =
this.#queueEmptyPromise
|| new Promise(( resolve ) => {
this.#resolveQueueEmpty = resolve
})
}
get queue() {
return this.#queue
}
/*set concurrency( value ) {
this.#concurrency = value
}*/
add( task, callback = promisifyTask ) {
// We're adding more tasks, so if there's a queueEmptyPromise,
// we should nullify it.
this.#queueEmptyPromise = null
this.#resolveQueueEmpty = null
const { promise, wrappedTask } = callback( task )
this.queue.push( wrappedTask )
this.next()
return promise
}
next() {
if (
this.#concurrentTaskCount >= this.concurrency
|| !this.queue.length
) {
if ( this.#concurrentTaskCount === 0 && this.#resolveQueueEmpty ) {
// If no tasks are running and there's a resolver waiting, call it.
this.#resolveQueueEmpty( false )
}
return
}
this.#concurrentTaskCount++
const task = this.queue.shift()
// eslint-disable-next-line promise/catch-or-return
task().finally(() => {
this.#concurrentTaskCount--
this.next()
})
}
}
/**
* Promisify a task.
* @param {Function} task The task to promisify.
* @returns {{promise: Promise, wrappedTask: Function}} The promisified task.
*/
function promisifyTask( task ) {
let resolve, reject
const promise = new Promise(( _resolve, _reject ) => {
resolve = _resolve
reject = _reject
})
return {
promise,
wrappedTask: async () => {
try {
resolve( await task())
} catch ( error ) {
reject( error )
throw error
}
}
}
}