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:
1 If callback defined:
if (typeof callback === 'function') {
callback();
}
Not compact at all!
2 Utility function:
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.
3 Using call
let myFunc = (callback) => {
// do something...
safeFunc(callback).call(this);
}
Not very user friendly.
4 Creating ID function
const ID = () => {};
let myFunc = (callback=ID) => {
// do something...
callback();
}
Has external dependency, not very functionnal, though probably the best choice.
Answer
// ES6 way:(default parameters)
function(callback=()=>{}) {
if(typeof callback === 'function') {
callback();
}
}
No comments:
Post a Comment