前端如何控制请求并发的数量

66 阅读1分钟

码上!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

const maxNum = 3//最大并发数,根据实际情况可自行调整
const allfilesList = [假设有一百条数据]

//请求单独处理
const aloneProcessingFn = (file) =>{
    return new Promise((resolve, reject) =>{
        //发起请求,成功res,失败rej
    })
}

//控制并发
const controlConcurrencyFn = (maxNum, allfilesList, aloneProcessingFn) => {
    const allAsyncTask = [];//存储所有的异步任务
    const executingTask = [];//存储正在执行的异步任务
    for(const item of allfilesList) {
        const pr = Promise.reslove().then(() => aloneProcessingFn(item))
        allAsyncTask.push(pr)
        if(maxNum <= allfilesList.length){
            const executePr = pr.then(() =>
                executingTask.splice(executingTask.indexOf(executePr), 1))
            ).catch(() => 
                executingTask.splice(executingTask.indexOf(executePr), 1)
            )
            executingTask.push(e)
            if (executingTask.length >= maxNum) {
                await Promise.race(executingTask)
            }
        }
    }
    return Promise.allSettled(allAsyncTask);
}

controlConcurrencyFn(maxNum, allfilesList, aloneProcessingFn).then(() =>{
    //所有接口完成
}).catch(() =>{
    //异常
})