请你说说实现一个 Scheduler 类,完成对Promise的并发处理,最多同时执行2个任务
区块链毕设网qklbishe.com为您提供问题的解答
请你说说实现一个 Scheduler 类,完成对Promise的并发处理,最多同时执行2个任务
class Scheduler{
constructor(){
this.queue = [];
this.maxNum = 2;
this.runNum = 0;
}
add(promiseCreator) {
this.queue.push(promiseCreator)
}
startTask(){
for(let i = 0; i< this.maxNum; i++){
this.request()
}
}
request(){
if(!this.queue || !this.queue.length || this.maxNum < this.runNum){
return
}
this.runNum ++
this.queue.shift()().then(() => {
this.runNum–
this.request()
})
}
}
const scheduler = new Scheduler()
const timeout = time => new Promise( resolve => setTimeout(resolve, time))
const addTask = (time,order) => {
scheduler.add(()=>timeout(time).then(()=>console.log(order)))
}
constructor(){
this.queue = [];
this.maxNum = 2;
this.runNum = 0;
}
add(promiseCreator) {
this.queue.push(promiseCreator)
}
startTask(){
for(let i = 0; i< this.maxNum; i++){
this.request()
}
}
request(){
if(!this.queue || !this.queue.length || this.maxNum < this.runNum){
return
}
this.runNum ++
this.queue.shift()().then(() => {
this.runNum–
this.request()
})
}
}
const scheduler = new Scheduler()
const timeout = time => new Promise( resolve => setTimeout(resolve, time))
const addTask = (time,order) => {
scheduler.add(()=>timeout(time).then(()=>console.log(order)))
}
addTask(1000, ‘1’);
addTask(500, ‘2’);
addTask(300, ‘3’);
addTask(400, ‘4’);
scheduler.taskStart()
27:06
以上就是关于问题请你说说实现一个 Scheduler 类,完成对Promise的并发处理,最多同时执行2个任务的答案
欢迎关注区块链毕设网-
专业区块链毕业设计成品源码,定制。
区块链NFT链游项目方科学家脚本开发培训