Skip to content

Instantly share code, notes, and snippets.

@cemdrk
Created April 24, 2025 13:15
Show Gist options
  • Save cemdrk/b907a2feb553a1ff5b208091ac099953 to your computer and use it in GitHub Desktop.
Save cemdrk/b907a2feb553a1ff5b208091ac099953 to your computer and use it in GitHub Desktop.
Promise Que in JS
class PromiseQue {
constructor(concurrentCount = 5) {
this.todo = [];
this.running = [];
this.maxTask = concurrentCount;
}
runNext(){
return ((this.running.length < this.maxTask) && this.todo.length);
}
run () {
if (this.running.length > 0) {
return;
}
while (this.runNext()) {
const promise = this.todo.shift();
promise.then(() => {
this.running = this.running.filter(p => p !== promise);
this.run();
});
this.running.push(promise);
}
}
async push(task) {
while (this.maxTask <= this.running.length) {
// wait for empty slot
await sleep(5);
}
this.todo.push(task);
this.run()
}
async waitAllFinished (){
while (this.running.length > 0) {
await sleep(5);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment