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
相关推荐
GISer_Jing3 小时前
前端面试通关:Cesium+Three+React优化+TypeScript实战+ECharts性能方案
前端·react.js·面试
落霞的思绪3 小时前
CSS复习
前端·css
咖啡の猫5 小时前
Shell脚本-for循环应用案例
前端·chrome
百万蹄蹄向前冲8 小时前
Trae分析Phaser.js游戏《洋葱头捡星星》
前端·游戏开发·trae
朝阳5818 小时前
在浏览器端使用 xml2js 遇到的报错及解决方法
前端
GIS之路8 小时前
GeoTools 读取影像元数据
前端
ssshooter9 小时前
VSCode 自带的 TS 版本可能跟项目TS 版本不一样
前端·面试·typescript
Jerry10 小时前
Jetpack Compose 中的状态
前端
dae bal10 小时前
关于RSA和AES加密
前端·vue.js
柳杉11 小时前
使用three.js搭建3d隧道监测-2
前端·javascript·数据可视化