Created
March 29, 2019 14:48
-
-
Save numfin/aa5c8e17c81ccaf10d5b51f586eaf79f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PromiseQueue { | |
constructor (limit = 20, cb = () => {}) { | |
/** @type {{promiseFn: () => Promise, cb: void}[]} */ | |
this.queue = [] | |
this.running = 0 | |
this.limit = limit | |
this.cb = cb | |
} | |
/** | |
* @param {() => Promise} promiseFn | |
* @param {void} cb | |
*/ | |
add (promiseFn, cb) { | |
if (this.running >= this.limit) { | |
this.queue.push({promiseFn, cb}) | |
} else { | |
++this.running | |
promiseFn().then(this.updateQueue(cb)) | |
} | |
} | |
printInfo () { | |
console.log(`running: ${this.running} queue: ${this.queue.length}`) | |
} | |
updateQueue (cb) { | |
this.printInfo() | |
return (data) => { | |
--this.running | |
cb(data) | |
this.printInfo() | |
const first = this.queue.shift() | |
if (!first && this.running === 0) { | |
this.cb() | |
} | |
if (first && first.promiseFn) { | |
++this.running | |
first.promiseFn().then(this.updateQueue(first.cb)) | |
} | |
} | |
} | |
} | |
// пример использования | |
const queue = new PromiseQueue(20, () => { | |
console.log('finished') | |
}) | |
for (let i = 0; i < 50; i++) { | |
const promise = async function () { | |
const a = i; | |
return new Promise (res => { | |
setTimeout(() => res(a), Math.random()*1000) | |
}) | |
} | |
queue.add(promise, (data) => { | |
console.log(data) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment