1
0
mirror of https://github.com/dzeiocom/libs.git synced 2025-07-30 00:39:52 +00:00

feat: Add better compaction system

Signed-off-by: Avior <git@avior.me>
This commit is contained in:
2024-12-03 16:33:41 +01:00
parent 78f75ec7d1
commit 91a6409e90
3 changed files with 2868 additions and 4 deletions

View File

@ -0,0 +1,47 @@
export default class Queue {
private queue = 0
private isPaused = false
private throwError?: Error
public constructor(
private maxQueueLength = 5,
private timeToWait = 500
) {}
public pause() {
this.isPaused = true
}
public start() {
this.isPaused = false
}
public updateCurrentQueueLength(len: number) {
this.queue = len
}
public async add<T = any>(...promises: Array<Promise<T>>) {
for (const promise of promises) {
while (this.queue >= this.maxQueueLength || this.isPaused) {
await new Promise((res) => setTimeout(res, this.timeToWait))
}
this.updateCurrentQueueLength(this.queue+1)
promise
.then(() => {
this.updateCurrentQueueLength(this.queue-1)
}).catch((e) => {
this.updateCurrentQueueLength(this.queue-1)
this.throwError = e
})
}
}
public async waitEnd() {
while (this.queue !== 0) {
if (this.throwError) {
throw this.throwError
}
await new Promise((res) => setTimeout(res, this.timeToWait))
}
}
}