Files
Folo/packages/shared/src/queue.ts
T
Innei 234471dfdf refactor: move to monorepo (#475)
* init

* fix: electron

Signed-off-by: Innei <i@innei.in>

* update

Signed-off-by: Innei <i@innei.in>

* fix: build

Signed-off-by: Innei <i@innei.in>

* fix: lint

Signed-off-by: Innei <i@innei.in>

* fix: test

Signed-off-by: Innei <i@innei.in>

---------

Signed-off-by: Innei <i@innei.in>
2024-09-18 20:54:48 +08:00

40 lines
880 B
TypeScript

export class AsyncQueue {
private maxConcurrent: number
private queue: (() => Promise<any>)[]
private activeCount: number
constructor(maxConcurrent: number) {
this.maxConcurrent = maxConcurrent
this.queue = []
this.activeCount = 0
}
private async runNext() {
if (this.activeCount >= this.maxConcurrent || this.queue.length === 0) {
return
}
this.activeCount++
const request = this.queue.shift()!
try {
return await request()
} catch (error) {
console.error("Request failed", error)
} finally {
this.activeCount--
this.runNext() // Start the next request after this one finishes
}
}
add(request: () => Promise<any>) {
this.queue.push(request)
return this.runNext()
}
addMultiple(requests: (() => Promise<any>)[]) {
this.queue.push(...requests)
this.runNext()
}
}