-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (36 loc) · 1.22 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
import { promisify } from "util"
const delay = promisify(setTimeout)
function mapAsync(items, cb, concurrency) {
const itemsMap = new Map(items.map((item, index) => [index, item]));
const itemsIterable = itemsMap.entries();
const resultsMap = new Map();
return new Promise((resolve, reject) => {
for (let i = 0; i < concurrency; i++) {
runner();
}
async function runner() {
while (true) {
try {
const { value: item, done } = itemsIterable.next()
if (done) break;
const [key, value] = item
const result = await cb(value)
resultsMap.set(key, result)
if (resultsMap.size === itemsMap.size) {
resolve([...resultsMap.values()])
break;
}
} catch (err) {
reject(err)
break;
}
}
}
})
}
const results = await mapAsync(['a', 'b', 'c', 'd', 'e', 'f'], async (item) => {
await delay(800)
console.log(`${item} item Done.`)
return item
}, 2)
console.log(results)