This repository was archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
113 lines (91 loc) · 2.27 KB
/
index.js
File metadata and controls
113 lines (91 loc) · 2.27 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
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
102
103
104
105
106
107
108
109
110
111
112
113
const wait = delay => new Promise(resolve => setTimeout(resolve, delay))
/**
* a queue to ensure async functions are called one after another in order, with option to run some functions in parallel
*/
class TaskQueue {
constructor () {
this._tasks = []
this._runningCount = 0
this._busy = false
this._paused = false
}
_push (task) {
this._tasks.push(task)
this._handleTasks()
}
_pop () {
return this._tasks.shift()
}
_peek () {
return this._tasks[0]
}
/**
* @returns the size of the queue, including already running tasks
*/
size () {
return this._tasks.length + this._runningCount
}
/**
* pauses the queue, no new tasks will get started after this
*/
pause () {
this._paused = true
}
/**
* resumes the queue
*/
resume () {
this._paused = false
this._handleTasks()
}
/**
* @returns the current pause state
*/
isPaused () {
return this._paused
}
async _handleTasks () {
await wait(0)
if (this._busy || this._paused || this.size() === 0) {
return
}
this._busy = true
const tasks = []
tasks.push(this._pop())
while (this.size() > 0) {
let candidate = this._peek()
if (candidate.group === null || candidate.group !== tasks[0].group) {
break
}
tasks.push(candidate)
this._pop()
}
const runner = tasks.map(({ fn, resolve, reject }) => (async () => {
++this._runningCount
try {
const response = await fn()
--this._runningCount
resolve(response)
} catch (error) {
--this._runningCount
reject(error)
}
})())
await Promise.all(runner)
this._busy = false
await this._handleTasks()
}
/**
* Pushes a new function onto the task-stack
* @param {function} fn the async function to push
* @param {String|Number|null} [group] the group identifier, consecutive tasks with the same group will be run in parallel or null for no group (will never run parallel)
* @returns a Promise that resolves the way fn would have resolved
*/
async push (fn, group = null) {
return new Promise((resolve, reject) => {
const task = { fn, group, resolve, reject }
this._push(task)
})
}
}
module.exports = TaskQueue