Jan Osch Jan Osch - 2 months ago 12
Node.js Question

How to ensure that a Node.js style callback it is called only once

I am looking for a utility that will ensure that only first call of the callback is executed.

I know you can do something like code below, but I am looking for this functionality in some popular utility like lodash/underscore/async that does exactly this.

function once(fun){
let called = false;

return function(){
if(!called){
const result = fun(...arguments);
called = true;
return result;
}
}
}

Answer

Underscore provides _.once

Lodash provides _.once

If you're using this for asynchronous code, you may find that promises provide a better abstraction.


I am looking for this functionality in some popular utility like lodash/underscore/async

Are you? Sounds like you didn't actually look. Did you try googling [your library name] [the name you gave your function]?

Comments