字节面试前端,菜鸡有道题不会,

JS实现一个带并发限制的异步调度器Scheduler,保证同时运行的任务最多有两个。完善代码中Scheduler类,使得以下程序能正确输出
class Scheduler {
add(promiseCreator) { ... }  // ...}
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
// 一开始,1、2两个任务进入队列// 500ms时,2完成,输出2,任务3进队// 800ms时,3完成,输出3,任务4进队// 1000ms时,1完成,输出1// 1200ms时,4完成,输出4

有人会吗?
全部评论
并发限制k版本,牛客咋不让贴代码了?? class Scheduler {     constructor(limit) {         this.queue = [];         this.limit = limit;         this.currentTaskCount = 0;     }     add(fn) {         return new Promise((resolve, reject) => {             this.queue.push([fn, resolve]);             this.exc();         })     }     exc() {         if (this.currentTaskCount < this.limit && this.queue.length) {             const [fn, resolve] = this.queue.shift();             this.currentTaskCount++;             Promise.resolve(fn()).then((result) => {                 resolve(result);                 this.currentTaskCount--;                 this.exc();             })         }     } }
2 回复 分享
发布于 2020-05-06 23:45
我在牛客面经看到过
点赞 回复 分享
发布于 2020-05-06 22:01

相关推荐

点赞 评论 收藏
分享
评论
1
6
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务