mirror of
https://github.com/austinried/subtracks.git
synced 2025-12-27 00:59:28 +01:00
32 lines
641 B
TypeScript
32 lines
641 B
TypeScript
type QueuedPromise = () => Promise<any>
|
|
|
|
class PromiseQueue {
|
|
maxSimultaneously: number
|
|
|
|
private active = 0
|
|
private queue: QueuedPromise[] = []
|
|
|
|
constructor(maxSimultaneously = 1) {
|
|
this.maxSimultaneously = maxSimultaneously
|
|
}
|
|
|
|
async enqueue<T>(func: () => Promise<T>) {
|
|
if (++this.active > this.maxSimultaneously) {
|
|
await new Promise(resolve => this.queue.push(resolve as QueuedPromise))
|
|
}
|
|
|
|
try {
|
|
return await func()
|
|
} catch (err) {
|
|
throw err
|
|
} finally {
|
|
this.active--
|
|
if (this.queue.length) {
|
|
this.queue.shift()?.()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export default PromiseQueue
|