2020-07-20 Promise编程:Scheduler
2020-07-20 本文已影响0人
苦庭
class Scheduler {
constructor(count) {
this.count = 2
this.queue = []
this.run = []
}
add(task) {
this.queue.push(task)
return this.schedule()
}
schedule() {
if (this.run.length < this.count && this.queue.length) {
const task = this.queue.shift()
const promise = task().then(() => { // promise 中定义了任务完成后在run数组中删除当前promise
this.run.splice(this.run.indexOf(promise), 1)
})
this.run.push(promise)
return promise
} else {
return Promise.race(this.run).then(() => this.schedule())
}
}
}
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(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')
// output: 2 3 1 4