import { $obj, computed, Context } from "../core/index.js"; export interface AsyncContextParent { /** * Called by async contexts to track a pending task. */ track(task: Promise): void; } /** * Represents pending operations in an asynchronously rendered tree. * * This can be used to wait until an entire async tree is rendered or to check if any unhandled errors occurred. */ export class AsyncContext { #parent: AsyncContextParent | undefined; #tasks = $obj(new Set>()); #errorHandlers = new Set(); constructor(parent?: AsyncContextParent) { this.#parent = parent; } /** * Reactively check if there are any pending tasks in this context. * * @example * ```tsx * *
Please wait...
*
* ``` */ pending = computed(() => this.#tasks.value.size > 0); /** * Track the specified task in this and all parent contexts. */ track(task: Promise): void { this.#parent?.track(task); this.#tasks.inert.add(task); this.#tasks.notify(); task.then(() => { this.#tasks.inert.delete(task); this.#tasks.notify(); }, error => { if (this.#errorHandlers.size > 0) { for (const errorHandler of this.#errorHandlers) { errorHandler.push(error); } } else { void Promise.reject(error); } this.#tasks.inert.delete(task); this.#tasks.notify(); }); } /** * Wait until all tracked tasks in this and all child contexts have completed. * * This also includes new tasks that are tracked while waiting. * * @throws Errors thrown by any tracked task or an {@link AsyncError} if multiple tasks failed. */ async complete(): Promise { const errors: unknown[] = []; this.#errorHandlers.add(errors); while (this.#tasks.value.size > 0) { await Promise.allSettled(this.#tasks.value); } this.#errorHandlers.delete(errors); if (errors.length === 1) { throw errors[0]; } else if (errors.length > 1) { throw new AsyncError(errors); } } /** * Create a new async context using the current context as parent. */ static fork(): AsyncContext { return new AsyncContext(ASYNC.current); } } /** * Thrown by {@link AsyncContext.complete} if multiple unhandled {@link errors} occurred. */ export class AsyncError extends Error { errors: unknown[]; constructor(errors: unknown[]) { super(); this.errors = errors; } } /** * Context for the current {@link AsyncContext}. */ export const ASYNC = new Context();