-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.js
44 lines (40 loc) · 995 Bytes
/
scheduler.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
/**
* 满足同时多个请求的时候,并发最多两个
*/
class Scheduler {
constructor() {
this.tasks = []
this.runCount = 0
}
add(promiseCreater) {
return new Promise((res, rej) => {
this.tasks.push([promiseCreater, res])
if (this.runCount < 2) {
this.run()
}
})
}
run() {
if(!this.tasks.length) return
let [task, res] = this.tasks.shift()
this.runCount++
task().then(resolve => {
this.runCount--
res()
this.run()
})
}
}
const timeout = (time) => new Promise(resolve => {
setTimeout(resolve, time)
})
const scheduler = new Scheduler()
const addTask = (time, order) => {
scheduler.add(() => timeout(time)).then(() => console.log(order))
}
addTask(500,'500ms run')
addTask(1000,'1000ms run')
addTask(500,'500ms run')
addTask(500,'500ms run')
addTask(500,'500ms run')
addTask(500,'500ms run')