I have several functions with optional callback:
let myFunc = (callback) => {
callback = callback || (() => {});
// do something...
callback();
}
What is the best way to write the callback default parameter?
None of the following solutions satisfy me much:
if (typeof callback === 'function') {
callback();
}
Not compact at all!
let safeFunc = (callback) => {
return callback || (() => {});
};
let myFunc = (callback) => {
// do something...
safeFunc(callback)();
}
but the problem is that in between this
has changed, and it matters in my case.
call
let myFunc = (callback) => {
// do something...
safeFunc(callback).call(this);
}
Not very user friendly.
const ID = () => {};
let myFunc = (callback=ID) => {
// do something...
callback();
}
Has external dependency, not very functionnal, though probably the best choice.
Calling directly Function()
constructor looks meaningful:
let myFunc = (callback = Function()) => {
// do something...
callback();
}
Calling Function()
returns a noop function:
let noopFunc = Function()
noopFunc() // => undefined
Here is another option.
if (callback) callback();
If you want to prevent calling the callback twice, another utility function here I've called callIt, it also handles passing arguments, and if this
is important also to prevent using bind, just pass this
..
function callIt(that, fn) {
if (fn) fn.apply(that, Array.prototype.slice.call(arguments,2));
}
//Test Object
function Test() {
this.test = 'Test';
}
Test.prototype.calltest = function (callback) {
callIt(this, callback, 1, 2, 3);
}
var t = new Test();
t.calltest(
function (a,b,c) {
console.log('this.test = ', this.test);
console.log('args = ', a, b, c);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With