zoukankan      html  css  js  c++  java
  • 一个简单的控制多并发的promise

    一个简单的控制多并发的promise

        class limitPromise {
            constructor(max) { 
                /*
                
                * @param _max 表示最大并发数
                * @param _taskQueue 表示任务队列
                */
                this._max = max;
                this._taskQueue= [] 
            }
            
            addTask (task) {
                this._taskQueue.push(task)
            }
    
            run() {
                // 如果任务队列为空,任务停止
                if(this._taskQueue.length === 0) {
                    return 
                }
                let min = Math.min(this._taskQueue.length,this._max);
                // 
                for(let i = 0;i<min; i++) {
                    this._max--;
                    let task = this._taskQueue.shift()
                    task().then(res=>{
                        console.log(res)
                    }).finally(()=>{
                        // 任务结束开始下一轮
                        this._max++;
                        this.run()
                    })
                }
            }
        }
    
    const limitPromiseObj = new limitPromise(5)
    
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第一个")
            },500)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第2个")
            },500)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第3个")
            },500)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第4个")
            },500)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第5个")
            },500)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第6个")
            },600)
    })
    })
    limitPromiseObj.addTask(function() {
        return new Promise((res,rej)=>{
            setTimeout(()=>{
                res("第7个")
            },700)
    })
    })
    
    limitPromiseObj.run()
    
    
  • 相关阅读:
    1063. Set Similarity
    A1047. Student List for Course
    A1039. Course List for Student
    最大公约数、素数、分数运算、超长整数计算总结
    A1024. Palindromic Number
    A1023. Have Fun with Numbers
    A1059. Prime Factors
    A1096. Consecutive Factors
    A1078. Hashing
    A1015. Reversible Primes
  • 原文地址:https://www.cnblogs.com/Rembang/p/14666342.html
Copyright © 2011-2022 走看看