js实现一个带并发限制的异步调度器scheduler

//js实现一个带并发限制的异步调度器scheduler,保证同时运行的任务最多有两个。 //www.nowcoder.com/discuss/599...

js 复制代码
class Scheduler {
    constructor() {
        this.limit = 2
        this.runningCount = 0
        this.taskQueue = []
    }
    add(promiseCreator) {
        return new Promise((resolve, reject) => {
            const taskWrapper = () => { //wrapper 封套
                promiseCreator()
                .then(resolve)
                .catch(reject)
                .finally(() => {
                    this.runningCount -= 1 // 任务完成后, 当前运行任务数减1
                    this.schedule(); // 调度下一个任务执行
                })
            }
            this.taskQueue.push(taskWrapper); // 将任务包装成函数并加入任务队列
            this.schedule();
        })
    }

    schedule() { 
        if (this.runningCount >= this.limit || this.taskQueue.length === 0) return // 达到并发限制或者队列为空时, 不再调度任务
        const task = this.taskQueue.shift(); 
        this.runningCount -= 1;
        task();
    }

}

const timeout = (time) => new Promise(resolve => {
    setTimeout(resolve, time)
})

const scheduler = new Scheduler()
const addTask = (time, order) => {
    scheduler.add(() => timeout(time))
        .then((res) => {
            console.log(order)
           // console.log(res)
        })
}

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
相关推荐
掘金安东尼10 分钟前
向大家介绍《开发者博主联盟》🚀
前端·程序员·github
火车叼位13 分钟前
div滚动条是否存在?用 v-scroll-detect 增加一个辅助class
前端
H_z_q240120 分钟前
web前端(HTML)银行汇款单的制作
前端·html
小宇的天下23 分钟前
Synopsys Technology File and Routing Rules Reference Manual (1)
java·服务器·前端
@PHARAOH24 分钟前
WHAT - Vercel react-best-practices 系列(四)
前端·react.js·前端框架
今天也要晒太阳47333 分钟前
对el-upload的上传文件显示名做长度限制
前端
Thomas游戏开发35 分钟前
分享一个好玩的:一次提示词让AI同时开发双引擎框架
前端·javascript·后端
NEXT0637 分钟前
别再折磨自己了!放弃 Redux 后,我用 Zustand + TS 爽到起飞
前端·react.js
donecoding38 分钟前
Sass 模块化革命:告别 @import,拥抱 @use 和 @forward
前端·css·代码规范
m0_7482523840 分钟前
Angular 2 数据显示方法
前端·javascript·angular.js