Created
April 24, 2025 13:15
-
-
Save cemdrk/b907a2feb553a1ff5b208091ac099953 to your computer and use it in GitHub Desktop.
Promise Que in JS
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 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