How to use the once function from lodash

Find comprehensive JavaScript lodash.once code examples handpicked from public code repositorys.

lodash.once is a utility function from the Lodash library that creates a new function that can only be called once, and then returns the result of that initial call on all subsequent calls.

6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
fork icon73
star icon711
watch icon29

282
283
284
285
286
287
288
289
290
291
module.exports.nthArg              = _.nthArg;
module.exports.nths                = _.nths;
module.exports.omit                = _.omit;
module.exports.omitBy              = _.omitBy;
module.exports.omitWhen            = _.omitWhen;
module.exports.once                = _.once;
module.exports.orderBy             = _.orderBy;
module.exports.over                = _.over;
module.exports.overArgs            = _.overArgs;
module.exports.overEvery           = _.overEvery;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.once work?

lodash.once works by creating a new function that can only be called once, and then returning the result of that initial call on all subsequent calls. When the new function created by lodash.once is called for the first time, it invokes the original function with the arguments provided, and saves the result. Subsequent calls to the function return the saved result without invoking the original function again. This behavior can be useful in situations where a function's output will not change after it has been called once, or where repeated calls to the function may be expensive or time-consuming. Note that lodash.once is part of the Lodash library, which provides a set of tools and utilities for working with arrays, objects, and functions in JavaScript.

11
12
13
14
15
16
17
18
19
20
const app = require('./server');

let timeoutHandler;
let killTime = 15;

const onConnect = _.once(() => {
  log('db connected in: %s', Date.now() - startTime);
  if (timeoutHandler) {
    clearTimeout(timeoutHandler);
  }
fork icon0
star icon3
watch icon0

+ 3 other calls in file

329
330
331
332
333
334
335
336
337
338
339
340
341
console.log(memoize(1, 2)); // => 3


const negate = _.negate(n => n > 0);
console.log(negate(1)); // => false


const once = _.once(() => console.log('hello'));
once();


const overArgs = _.overArgs((x, y) => [x, y], [n => n + 1, n => n + 2]);
console.log(overArgs(1, 2)); // => [2, 4]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
const _ = require("lodash");

function expensiveOperation() {
  console.log("Performing expensive operation...");
  return 42;
}

const performOnce = _.once(expensiveOperation);

console.log(performOnce()); // Performing expensive operation... 42
console.log(performOnce()); // 42
console.log(performOnce()); // 42

In this example, we define a function called expensiveOperation that logs a message to the console and returns a constant value (42). We then use lodash.once to create a new function called performOnce that can only be called once. We pass expensiveOperation as an argument to _.once, which creates a new function that will invoke expensiveOperation on its first call and save the result. We then call performOnce three times in a row, and observe that the message "Performing expensive operation..." is only logged once, while the result 42 is returned on all subsequent calls. Note that lodash.once can be used with any function, including functions that take arguments, and can be customized with additional options such as a before function to be called before the first invocation, or a after function to be called after the final invocation.

89
90
91
92
93
94
95
96
97
98
99
  } else {
    return Boom.internal();
  }
}


const checkSSRMetricsReporting = _.once(topOpts => {
  const reporting = _.get(topOpts, "reporting", {});
  if (!reporting.enable || !reporting.reporter) {
    // eslint-disable-next-line
    console.log(
fork icon309
star icon0
watch icon49

+ 8 other calls in file

209
210
211
212
213
214
215
216
217
218
});

const encoding = options.encoding || 'utf8';

if (typeof callback === 'function') {
  callback = callback && once(callback);

  jws.createSign({
    header: header,
    privateKey: secretOrPrivateKey,
fork icon0
star icon0
watch icon1

1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
  return callback(null, user)
}
// If the refresh takes too long then return the current
// features. Note that the user.features property may still be
// updated in the background after the callback is called.
callback = _.once(callback)
const refreshTimeoutHandler = setTimeout(() => {
  req.session.feature_refresh_failed = { reason: 'timeout', at: new Date() }
  metrics.inc('features-refresh', 1, {
    path: 'load-editor',
fork icon0
star icon0
watch icon202

+ 15 other calls in file

4
5
6
7
8
9
10
11
12
13
14
15
const { minimizePath } = require("./helpers");


let CACHE = null;
const PATH = path.join(process.cwd(), "../REC_DB.json");


const startDb = _.once(async () => {
  try {
    try {
      await fs.promises.access(PATH, fs.constants.R_OK | fs.constants.W_OK);
      CACHE = JSON.parse(await fs.promises.readFile(PATH, "utf8"));
fork icon0
star icon0
watch icon1

+ 11 other calls in file

140
141
142
143
144
145
146
147
148
149
    }
  })
},

_runAndWaitForContainer(options, volumes, timeout, _callback) {
  const callback = _.once(_callback)
  const { name } = options

  let streamEnded = false
  let containerReturned = false
fork icon0
star icon0
watch icon202

+ 5 other calls in file

663
664
665
666
667
668
669
670
671
672
673
674
})


const createVideoRecording = function (videoName, options = {}) {
  const outputDir = path.dirname(videoName)


  const onError = _.once((err) => {
    // catch video recording failures and log them out
    // but don't let this affect the run at all
    return errors.warning('VIDEO_RECORDING_FAILED', err.stack)
  })
fork icon0
star icon0
watch icon0

170
171
172
173
174
175
176
177
178
179
180
let negate1 = _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
console.log('negate1--->', negate1);
//negate1---> [ 1, 3, 5 ]


//_.once(func)
// var initialize = _.once(createApplication);
// initialize();
// initialize();
//

fork icon0
star icon0
watch icon0

+ 3 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)