Description
Often times you will be fetching many results this causes strain on the system, this can be avoided with either a for loop with an await inside it or by creating a runner.
?
Reach for when
You want to only allow 2->N calls at a time
Code
class Runner {
constructor(max) {
this.running = 0
this.max = max
this.pending = []
}
doNext() {
if (this.running < this.max && this.pending.length > 0) {
this.running += 1
this.pending.shift()()
}
}
push(task) {
return new Promise((resolve, reject) => {
this.pending.push(() =>
task()
.then(resolve)
.catch(reject)
.finally(() => {
this.running -= 1
this.doNext()
})
)
this.doNext()
})
}
}