问答题1180/1593实现有并行限制的Promise调度器

难度:
2021-07-06 创建

参考答案:

1class Scheduler { 2 constructor() { 3 this.queue = []; 4 this.maxCount = 2; 5 this.runCounts = 0; 6 } 7 add(promiseCreator) { 8 this.queue.push(promiseCreator); 9 } 10 taskStart() { 11 for (let i = 0; i < this.maxCount; i++) { 12 this.request(); 13 } 14 } 15 request() { 16 if (!this.queue || !this.queue.length || this.runCounts >= this.maxCount) { 17 return; 18 } 19 this.runCounts++; 20 21 this.queue.shift()().then(() => { 22 this.runCounts--; 23 this.request(); 24 }); 25 } 26} 27 28const timeout = time => new Promise(resolve => { 29 setTimeout(resolve, time); 30}) 31 32const scheduler = new Scheduler(); 33 34const addTask = (time,order) => { 35 scheduler.add(() => timeout(time).then(()=>console.log(order))) 36} 37 38 39addTask(1000, '1'); 40addTask(500, '2'); 41addTask(300, '3'); 42addTask(400, '4'); 43scheduler.taskStart() 44// 2 45// 3 46// 1 47// 4

最近更新时间:2021-07-07

赞赏支持

预览

题库维护不易,您的支持就是我们最大的动力!