另一页

Promise限流

function* getPromise() {
    while (true) {
        let r = Math.random() * 1000
        yield new Promise((resolve) => {
            setTimeout(() => { resolve() }, r)
        }).then(() => { console.log('fin in ' + r, promiseCount, ++count, allPromise) })
    }
}

let getP = getPromise()
let promiseCount = 0
const maxCount = 10
let allPromise = 100
let count = 0

function sendNextPromise() {

    if (promiseCount < maxCount) {
        promiseCount++
        allPromise--
        getP.next().value.then(() => {
            promiseCount--

            if (allPromise > 0) { sendNextPromise() }

        })

    }

}

for (let i = 0; i < 100; i++) {

    sendNextPromise()
}