Write a once function
Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.
Initialisation code, such as opening a connection, should run the first time it is needed and never again. Wrap the function so later calls return the saved result.
const once = (fn) => {
let called = false;
let result;
return function (...args) {
if (!called) {
result = fn.apply(this, args);
called = true;
}
return result;
};
};
const connect = once(() => {
console.log('connecting');
return 42;
});
console.log(connect());
console.log(connect());connecting
42
42The closure holds called and result where no other code can reach them. called is set after the call returns, so if fn throws, nothing is cached and the next call tries again. Set it before the call if a failed first run should count as the one run.
The wrapper keeps this through Function.prototype.apply. If the function is async, the cached result is the same promise every time, including a rejected one.