-
Notifications
You must be signed in to change notification settings - Fork 0
/
second-solution.js
39 lines (30 loc) · 915 Bytes
/
second-solution.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
'use strict'
const mapAsync = (arr, cb, concurrency) => {
let running = 0
const taskQueue = []
const runTask = (task) => {
return new Promise((resolve, reject) => {
taskQueue.push(() => task().then(resolve, reject))
process.nextTick(consumer)
})
}
const consumer = async () => {
while(running < concurrency && taskQueue.length !== 0) {
console.log("spanning new consumer")
running ++
const curr = taskQueue.shift()
await curr()
running --
console.log("shutting down consumer")
consumer()
}
}
return Promise.all(arr.map(item => runTask(() => cb(item))))
}
const mapFn = x => Promise.resolve(x * 2)
const arr = [1, 2, 3, 4]
mapAsync(arr, mapFn, 2)
.then(result => console.log(result))
.catch(e => {
console.error('Error happened', e)
})