-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
46 lines (43 loc) · 1.2 KB
/
index.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
/*
- Migrate Task Queue class internals from promises to async/await
- Original found at:
https://github.com/PacktPublishing/Node.js-Design-Patterns-Third-Edition/blob/master/05-asynchronous-control-flow-patterns-with-promises-and-async-await/05-promises-web-spider-v4/TaskQueue.js
*/
export class TaskQueue {
constructor (concurrency) {
this.concurrency = concurrency
this.running = 0
this.queue = []
}
runTask (task) {
return new Promise((resolve, reject) => {
this.queue.push(async () => {
try{
resolve(task())
} catch (err) {
reject(err)
}
})
/*
Was using Process.nextTick for async functionality
The next() function needed to be async using async keyword
*/
this.next()
})
}
async next () {
while (this.running < this.concurrency && this.queue.length) {
/*
If function did not await next task, it would execute only parent
link. adding the await keyword to task added the complete async functionality
*/
const task = this.queue.shift()
await task
task().finally(() => {
this.running--
this.next()
})
this.running++
}
}
}