promise并发
class Scheduler{ //正在执行的顺序 constructor(max){ //当前正在执行的任务个数 this._count = 0; //最大上限数 this._max = max; this._taskQueue = []; } add(promiseCreator){ const task = this._createTask(promiseCreator); if(this._count >= this._max){//正在执行任务已满,放入任务队列中 this._taskQueue.push(task); }else{ task();//立即执行 } } _createTask(promiseCreator){ return ()=>{//返回一个函数 promiseCreator().then(()=> {//立刻执行promiseCreator this._count--; if (this._taskQueue.length) { let task = this._taskQueue.shift(); task(); } } ); this._count++; } } } const timeout = (time) => new Promise(resolve => { setTimeout(resolve,time); }); const scheduler = new Scheduler(2); const addTask = (time,order)=>{ scheduler.add(()=>timeout(time).then(()=>console.log(order))); }; addTask(1000,"1"); addTask(500,"2"); addTask(300,"3"); addTask(400,"4");