Created
December 13, 2023 09:29
-
-
Save ztrehagem/eacd997a55222848aa38a33bbab971b9 to your computer and use it in GitHub Desktop.
This file contains 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
type Task<T> = () => Promise<T>; | |
export class TaskPool { | |
#isReady: boolean; | |
#current: Task<unknown> | null; | |
readonly #queue: Task<unknown>[]; | |
constructor( | |
params: { | |
readonly isReady?: boolean; | |
} = {}, | |
) { | |
this.#isReady = params.isReady ?? false; | |
this.#current = null; | |
this.#queue = []; | |
} | |
notifyReady(): void { | |
this.#isReady = true; | |
this.#check(); | |
} | |
#check(): void { | |
if (this.#current == null && this.#isReady) { | |
this.#current = this.#queue.shift() ?? null; | |
void this.#current?.().finally(() => { | |
this.#current = null; | |
this.#check(); | |
}); | |
} | |
} | |
waitFor<T>(task: Task<T>): Promise<T> { | |
return new Promise((resolve, reject) => { | |
this.#queue.push(() => task().then(resolve).catch(reject)); | |
this.#check(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment