Skip to content

Instantly share code, notes, and snippets.

@ztrehagem
Created December 13, 2023 09:29
Show Gist options
  • Save ztrehagem/eacd997a55222848aa38a33bbab971b9 to your computer and use it in GitHub Desktop.
Save ztrehagem/eacd997a55222848aa38a33bbab971b9 to your computer and use it in GitHub Desktop.
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