// 并发优化10个请求,同时最多只能执行3个
// 输入:promise数组,limit参数
// 存储 reqPool - 并发池
// 思路:塞入 + 执行
function qpsLimit (requestPipe, limitMax=3) {
let reqPool = []
// 往并发池里塞入请求
const add = () => {
let req = requestPipe.shift()
reqPool.push(req)
}
// 执行实际请求
const run = () => {
if (requestPipe.length === 0) return
let finsh = Promise.race(reqPool)
finsh.then(res => {
let done = reqPool.indexOf(finsh)
reqPool.splice(done, 1)
add()
})
run()
}
while (reqPool.length < limitMax) {
add()
}
run()
}
并发优化请求
最新推荐文章于 2024-06-06 09:23:23 发布