异步任务并发量
2023-03-21 15:00:37
现在有下面的代码 实现一个可以控制异步任务并发执行的函数 asyncPool
ts
async function asyncPool({ limit, items }) {
// write your code
}
async function sleep(n, name = 'test') {
return new Promise(resolve => {
console.log(n, name, 'start')
setTimeout(() => {
console.log(n, name, 'end', '-----------')
resolve({ n, name })
}, n * 1000)
})
}
async function start() {
await asyncPool({
limit: 2,
items: [
() => sleep(1, '吃饭'),
() => sleep(3, '睡觉'),
() => sleep(5, '写代码'),
() => sleep(3.5, '打游戏'),
() => sleep(4, '学习')
]
})
console.log('all end')
}
start()
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
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
输入了五个异步任务 同时只能执行两个 且每个异步任务的时间都不同
ts
async function asyncPool({ limit, items }) {
const promises = []
const pool = new Set()
for (const item of items) {
const fn = async item => await item()
const promise = fn(item)
promises.push(promise)
pool.add(promise)
const clean = () => pool.delete(promise)
promise.then(clean, clean)
if (pool.size >= limit) {
await Promise.race(pool)
}
// Promise. race
}
return Promise.all(promises)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18