-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathlimit-promise.js
More file actions
48 lines (43 loc) · 944 Bytes
/
limit-promise.js
File metadata and controls
48 lines (43 loc) · 944 Bytes
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
async function asyncPool({
limit,
items,
fn
}) {
const promises= []
const pool = new Set()
for (const item of items) {
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)
}
return Promise.all(promises)
}
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(){
asyncPool({
limit: 2,
items: [
()=> sleep(1,'吃饭'),
()=> sleep(3,'睡觉'),
()=> sleep(5,'打游戏'),
()=> sleep(3.5,'学习算法'),
()=> sleep(4,'学习Vue和React'),
],
async fn(item){
return await item()
}
})
}
// @think 如果任务有优先级呢
start()