Run A Function Only Once

Wrap sync and async functions so initialization runs at most once, sharing the cached result or in-flight promise.

JavascriptResilience

Code

javascriptsnippet
23 lines
export function once(fn) {
  if (typeof fn !== "function") throw new TypeError("fn must be a function");
  let called = false;
  let result;
  return function onceWrapper(...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

export function onceAsync(fn) {
  if (typeof fn !== "function") throw new TypeError("fn must be a function");
  let promise;
  return function onceAsyncWrapper(...args) {
    if (!promise) {
      promise = Promise.resolve().then(() => fn.apply(this, args));
    }
    return promise;
  };
}

Inside the snippet

Run A Function Only Once comes down to the functions once, onceWrapper, onceAsync and onceAsyncWrapper.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Watch out for

  • The guard typeof fn !== "function" short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads export function once(fn)

The surface worth importing is once; the helpers around it are private to the snippet.

Key statements

promise = Promise.resolve().then(() => fn.apply(this, args));
if (typeof fn !== "function") throw new TypeError("fn must be a function");
return function onceWrapper(...args) {
  if (!called) {
    called = true;
    result = fn.apply(this, args);
  }
  return result;
};

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
`TypeError` is raised at the guard (`typeof fn !== "function"`), so invalid state never reaches the main logic.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `once`, `onceWrapper`, `onceAsync` at load time.