Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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());
Text
connecting
42
42

The 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.

Taggednode 24
Share

More snippets

Functions

Use a generator to paginate any API

Use a generator to paginate any API in JavaScript, hiding the page loop behind for await so callers see one stream of items. Works in Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.