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
相关推荐
mCell1 天前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 天前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript