JavaScript控制Promise并发数

171 阅读1分钟

实现

通过Promise.allSettled+递归的方法,在请求队列不为空时,不断的请求。

代码

//模拟Promise请求
function request(url, time = 1) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('请求结束:'+url);
            if(Math.random() > 0.5){
                resolve('成功')
            }else{
                reject('错误;')
            }
        }, time * 1e3)
    })
}
//通过类来控制并发数
class PromiseController {
    constructor(requestList,maxRequestNum) {
        //请求数组
        this.requestList = requestList
        //最大并发数
        this.maxRequestNum = Math.min(maxRequestNum, requestList.length) 
        //储存结果
        this.responseList = []
        //请求池
        this.requestPool = []
    }
    addPool() {
        const list = this.requestList.splice(this.maxRequestNum)
        //返回promise并添加到请求池中
        this.requestPool = this.requestList.map(el => {
            return el()
        })
        this.requestList = list
    }
  	//递归执行,跑完后返回结果
    async run() {
        if(!this.isFinish()) {
            this.addPool()
            try {
                const res = await Promise.allSettled(this.requestPool)
                this.responseList.push(...res)
                return await this.run()
            }catch(err) {
                console.log('err',err)
            }
        }else {
            return this.responseList
        }
    }
    isFinish() {
        return this.requestList.length <= 0 && this.requestPool.length <= 0
    }
}
const requests = [() => request('1'),
() => request('2'),
() => request('3'),
() => request('4')]

const pc = new PromiseController(requests,3)

pc.run().then(res => {
    console.log('response',res)
})