JS实现AsyncPool连接池

215 阅读1分钟
const pro1 = () => {
    console.log("1")
}
const pro2 = () => {
    setTimeout(()=>{
        console.log("2")
    },1000)
}
const pro3 = () => {
    console.log("3")
}
const pro4 = () => {
    console.log("4")
}
const pro5 = () => {
    console.log("5")
}
const pro6 = () => {
    console.log("6")
}
//测试的代码
let arr = [pro1, pro2, pro3, pro4, pro5, pro6]

const AsyncPool = async(arr, limit) => {
    let execting = []
    for(const item of arr){
        let pro = ()=>{
            return new Promise(resolve=>{
                resolve(item)
            })
        }
        if(arr.length>=limit){
            const e = pro().then(ans=>{
                ans()
                execting.splice(execting.indexOf(e),1)
            })
            execting.push(e)
            if(execting.length>=limit){
                await Promise.race(execting)
            }
        }
    }
}
AsyncPool(arr,3)
/**
先输出
13
再输出
456
最后输出
2
*/