Skip to content

Instantly share code, notes, and snippets.

@numfin
Created March 29, 2019 14:48
Show Gist options
  • Save numfin/aa5c8e17c81ccaf10d5b51f586eaf79f to your computer and use it in GitHub Desktop.
Save numfin/aa5c8e17c81ccaf10d5b51f586eaf79f to your computer and use it in GitHub Desktop.
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