JS实现一个带并发限制的异步调度器Scheduler

class PromiseQueue {
    constructor(concurrency) {
        this.concurrency = concurrency;
        this.queue = [];
        this.running = 0;
        this.isExecuting = false;
    }

    add(promiseGenerator) {
        this.queue.push(promiseGenerator);
        this.run();
    }

    run() {
        while (this.running < this.concurrency && this.queue.length > 0) {
            const promiseGenerator = this.queue.shift();

            if (typeof promiseGenerator === 'function') {
                this.running++;

                promiseGenerator().then(() => {
                    this.complete();
                }).catch(() => {
                    this.complete();
                });
            }
        }
    }

    complete() {
        this.running--;
        this.run();
    }
}

另一个答案,参考《 实现一个带并发限制的promise异步调度器

function Scheduler(){
    this.list=[]
    this.add=function(promiseCreator){
       this.list.push(promiseCreator)
    }
    
    this.maxCount=2;
 
    
    var tempRunIndex=0;
 
    this.taskStart=function(){
       for(var i =0 ;i<this.maxCount;i++){
           request.bind(this)()
       }
    }
 
    function request(){
      
        if(!this.list || !this.list.length || tempRunIndex>=this.maxCount){
            return
        }
       
        tempRunIndex++
        this.list.shift()().then(()=>{
            tempRunIndex--
            request.bind(this)()
        })
    }
}
 
function timeout(time){
    return new Promise(resolve=>{
        setTimeout(resolve,time)
    })
}
 
var scheduler = new Scheduler()
 
function addTask(time,order){
    scheduler.add(()=>timeout(time).then(()=>console.log(order)))
}
 
 
addTask(1000,1)
addTask(500,2)
addTask(300,3)
addTask(400,4)
 
scheduler.taskStart()
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值