-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (69 loc) · 2.1 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
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
'use strict'
class TaskQueuePCPromisified {
consumerQueue = []
taskQueue = []
constructor(concurrent) {
for(let i = 0; i < concurrent; i++) {
this.consumer()
}
}
async consumer() {
const _this = this
return new Promise((resolve, reject) => {
(function loop(){
_this.getNextTask()
.then(currTask => currTask())
.catch(err => reject(err))
.then(() => process.nextTick(loop.bind(_this)))
})()
})
}
async getNextTask() {
return new Promise((resolve, reject) => {
if(this.taskQueue.length !== 0) {
const currTask = this.taskQueue.shift()
return resolve(currTask)
}
this.consumerQueue.push(resolve)
})
}
async runTask(task) {
return new Promise((resolve, reject) => {
const taskWrapper = () => {
const taskPromise = task()
taskPromise.then(resolve, reject)
return taskPromise
}
if(this.consumerQueue.length !== 0) {
const currConsumer = this.consumerQueue.shift()
currConsumer(taskWrapper)
} else {
this.taskQueue.push(taskWrapper)
}
})
}
}
const delay = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), ms)
})
}
const taskA = async () => {
console.log("starting task a")
await delay(5000)
return Promise.resolve('a')
}
const taskB = async () => {
console.log("starting task b")
await delay(1000)
return Promise.resolve('b')
}
const taskC = async () => {
console.log("starting task c")
await delay(2000)
return Promise.reject(new Error("Error happened while resolving task c"))
}
const queue = new TaskQueuePCPromisified(2)
queue.runTask(taskA).then(data => console.log(data))
queue.runTask(taskB).then(data => console.log(data))
queue.runTask(taskC).then(data => console.log(data)).catch((e) => console.error(e))