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
相关推荐
幼儿园技术家30 分钟前
多方案统一认证体系对比
前端
十一.36635 分钟前
83-84 包装类,字符串的方法
前端·javascript·vue.js
over6971 小时前
深入解析:基于 Vue 3 与 DeepSeek API 构建流式大模型聊天应用的完整实现
前端·javascript·面试
用户4099322502121 小时前
Vue3计算属性如何通过缓存特性优化表单验证与数据过滤?
前端·ai编程·trae
接着奏乐接着舞1 小时前
react useMeno useCallback
前端·javascript·react.js
码农阿豪1 小时前
Vue项目构建中ESLint的“换行符战争”:从报错到优雅解决
前端·javascript·vue.js
xhxxx2 小时前
AI打字机的秘密:一个 buffer 如何让机器学会“慢慢说话”
前端·vue.js·openai
韩曙亮2 小时前
【Web APIs】BOM 浏览器对象模型 ⑥ ( location 对象 | location 常用属性和方法 | URL 简介 )
前端·javascript·dom·url·bom·location·浏览器对象模型
用户21411832636022 小时前
CC-Switch配置切换神器:5秒搞定多设备同步,坚果云让配置永不丢失
前端
勤奋的懒洋洋3502 小时前
前端实现多个图片打包下载
前端