class Schedule{
constructor(maxtask){
this.list = [];
this.maxtask = maxtask;
this.worknum = 0;
};
add(...task){
this.list.push(...task)
};
start(){
for(let i = 0;i<this.maxtask;i++){
this.donext()
}
};
donext(){
if(this.list.length&&this.worknum<this.maxtask){
this.worknum++;
const p = this.list.shift();
p().then(()=> {
this.worknum--;
this.donext()
})
}
}
}
const schedule = new Schedule(2);
function f1(){
return new Promise((res1,rej) => {
setTimeout(res => {
console.log('p1');
res1()
},1000)
})
}
function f2(){
return new Promise((res1,rej) => {
setTimeout(res => {
console.log('p2');
res1()
},1000)
})
}
function f3(){
return new Promise((res1,rej) => {
setTimeout(res => {
console.log('p3');
res1()
},1000)
})
}
function f4(){
return new Promise((res1,rej) => {
setTimeout(res => {
console.log('p4');
res1()
},1000)
})
}
schedule.add(f1,f2,f3,f4)
schedule.start()
//先打印p1,p2之后才打印p3,p4
Promise实现并发
最新推荐文章于 2021-07-31 20:27:30 发布