Lazy Async Init Single Promise
The first call starts one init promise that every caller shares, and a rejection clears it so the next call retries instead of failing forever.
Code
// Lazy async init: a single expensive setup starts on the first call, every
// caller awaits the same promise, and a rejection resets it for a retry
let clientPromise = null;
let attempts = 0;
function connect(attempt) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (attempt === 1) reject(new Error('config missing'));
else resolve({ endpoint: 'db://local', ready: true });
}, 5);
});
}
function getClient() {
if (!clientPromise) {
attempts += 1;
clientPromise = connect(attempts).catch((err) => {
clientPromise = null; // drop the poisoned promise so a retry can start
throw err;
});
}
return clientPromise;
}
async function main() {
const firstCall = getClient();
console.log('callers share one promise:', firstCall === getClient());
try {
await firstCall;
} catch (err) {
console.log('first init failed:', err.message);
}
const client = await getClient();
console.log('retry attempt:', attempts, client.endpoint);
const cached = await getClient();
console.log('settled init reused:', cached === client, 'attempts still:', attempts);
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
callers share one promise: true
first init failed: config missing
retry attempt: 2 db://local
settled init reused: true attempts still: 2How the snippet works
The working surface is the functions connect, getClient and main — everything else is wiring.
The asynchronous flow is linearized with await, keeping failure handling local.
It builds and returns a fresh value rather than reusing its inputs.
Applying it
The entry-point signature is function connect(attempt)
The demo output is labeled (callers share one promise:, first init failed:, retry attempt:); each label names the call that printed it.
Treat main as the orchestrator calling getClient in a fixed order.
Statements that matter
clientPromise = connect(attempts).catch((err) => {
clientPromise = null; // drop the poisoned promise so a retry can start
throw err;
});
return new Promise((resolve, reject) => {
setTimeout(() => {
if (attempt === 1) reject(new Error('config missing'));
else resolve({ endpoint: 'db://local', ready: true });
}, 5);
});
const client = await getClient();
Interactive Tools for This Topic
FAQ
- Does `connect` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What does Lazy Async Init Single Promise print when run?
- Running the file directly is enough — expect labeled output lines such as `callers share one promise:`, `first init failed:`, `retry attempt:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.