The type of value to store.
A new LazyAsync<T> instance.
// Basic usage
const lazy = LazyAsync(async () => {
const response = await fetch('/api/data');
return await response.json();
});
const data = await lazy.force();
// Database connection singleton
const db = LazyAsync(async () => {
console.log('Connecting to database...');
return await Database.connect(connectionString);
});
async function getDb(): Promise<Database> {
return await db.force();
}
// Multiple calls - connection happens only once
const [db1, db2] = await Promise.all([getDb(), getDb()]);
console.log(db1 === db2); // true
// Configuration loader
const config = LazyAsync(async () => {
const response = await fetch('/api/config');
if (!response.ok) {
throw new Error(`Failed to load config: ${response.status}`);
}
return await response.json() as Config;
});
// Used throughout the app
async function getApiEndpoint(): Promise<string> {
const cfg = await config.force();
return cfg.apiEndpoint;
}
Creates a new
LazyAsync<T>with the given async initialization function.The function is called at most once, on first access via
force(). Concurrent calls toforce()before initialization completes will wait for the single initialization to finish.