happy-rusty
    Preparing search index...

    Function OnceAsync

    • Creates a new empty OnceAsync<T>.

      OnceAsync<T> stores Awaited<T>, matching JavaScript's Promise flattening behavior. This means OnceAsync<Promise<number>> and OnceAsync<number> behave identically.

      Type Parameters

      • T

        The type parameter. The actual stored type is Awaited<T>.

      Returns OnceAsync<T>

      A new uninitialized OnceAsync.

      // Basic usage
      const once = OnceAsync<string>();
      await once.getOrInit(async () => 'hello');
      console.log(once.get().unwrap()); // 'hello'
      // Async lazy singleton pattern
      const db = OnceAsync<Database>();

      async function getDb(): Promise<Database> {
      return await db.getOrInit(async () => {
      console.log('Connecting to database...');
      return await Database.connect(connectionString);
      });
      }

      // Multiple calls - connection happens only once
      const [db1, db2] = await Promise.all([getDb(), getDb()]);
      console.log(db1 === db2); // true
      // Fallible async initialization
      const config = OnceAsync<Config>();

      async function loadConfig(): Promise<Result<Config, Error>> {
      return await config.getOrTryInit(async () => {
      try {
      const response = await fetch('/api/config');
      if (!response.ok) {
      return Err(new Error(`HTTP ${response.status}`));
      }
      return Ok(await response.json());
      } catch (e) {
      return Err(e as Error);
      }
      });
      }