The type parameter. The actual stored type is Awaited<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);
}
});
}
Creates a new empty
OnceAsync<T>.OnceAsync<T>storesAwaited<T>, matching JavaScript's Promise flattening behavior. This meansOnceAsync<Promise<number>>andOnceAsync<number>behave identically.