Execute a function once
Run a function on the first call and return that result afterwards.
function once(fn) {
let done = false, result;
return (...args) => {
if (!done) { result = fn(...args); done = true; }
return result;
};
}
Usage
let connections = 0;
const connect = once(() => ({ id: ++connections }));
connect(); // → { id: 1 }
connect(); // → { id: 1 }
connections; // → 1
Know the limits
- Typical use: create one API client or connection pool lazily, on first use.
- If fn throws, done stays false and the next call tries again. A rejected promise, however, is a result and is kept.
- The original forwarded no arguments and overwrote fn with its result.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Execute a function once from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Forwards arguments and keeps the result separate from the function; a throwing first call can be retried. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Logical xor operator — True when exactly one of two values is truthy.
- Identity function — Return the argument unchanged.
- Box handler — Chain transformations on a value, then unwrap the result.