call-once-promise
v1.0.1
Published
Enforce a function or promise resolver to execute exactly once, caching results or retrying failures.
Maintainers
Readme
call-once-promise
Why use call-once-promise? When initializing systems (e.g. database connect, config read), multiple parallel requests can trigger duplicate connection routines. They need to run once, share the promise, and retry if they fail.
A wrapper that ensures an async function runs exactly once, sharing the active promise across all callers and resetting upon failure to allow retries.
⚡ Features
- Guarantees single execution for async functions
- Caches active promise and resolves all concurrent callers
- Resets on failure so subsequent attempts can retry
📦 Installation
npm i call-once-promise🚀 Usage
import { oncePromise } from 'call-once-promise';
let calls = 0;
const connectDb = oncePromise(async () => {
calls++;
console.log('Connecting to database...');
return 'ConnectionPool';
});
// Call simultaneously
const [c1, c2, c3] = await Promise.all([connectDb(), connectDb(), connectDb()]);
console.log('Calls executed:', calls); // 1⚙️ API Reference
oncePromise(fn)
fn:() => Promise<T>- Target async initializer.- Returns a guarded function resolving a shared
Promise<T>.
📺 Demonstration

📄 License
MIT License.
