Fork me on github

控制请求的并发数

1. 使用计数器维护当前的并发数

2. 使用递归的方式继续后续的请求

3. 注意结果的顺序性

 

const promiseList = [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000].map((item) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(item)
            resolve(item)
        }, item)
    })
})

function multiRequest(promiseList = [], maxNum) {
    let len = promiseList.length
    let result = new Array(len).fill(false)
    let count = 0

    return new Promise((resolve, reject) => {
        while(count < maxNum) {
            next()
        }

        function next() {
            let current = count++
            console.log('count = ', count)
            if (current >= len) {
                !result.includes(false) && resolve(result)
                return
            }
            promiseList[current].then((res) => {
                result[current] = res
                if (current < len) {
                    next()
                }
            }).catch((err) => {
                console.log(`结束 ${current}`, new Date().toLocaleString());
                result[current] = err;
                // 请求没有全部完成, 就递归
                if (current < len) {
                  next();
                }
            })
        }
    })
}

const promiseLimit = multiRequest(promiseList, 3)
promiseLimit.then((res) => {
    console.log(res)
    }
)

 

posted @ 2023-07-24 00:55  zjy4fun  阅读(19)  评论(0编辑  收藏  举报