Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Default value parameter for callback [duplicate]

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.

like image 420
Augustin Riedinger Avatar asked Nov 30 '16 13:11

Augustin Riedinger


2 Answers

Calling directly Function() constructor looks meaningful:

let myFunc = (callback = Function()) => {
  // do something...
  callback();
}

Calling Function() returns a noop function:

let noopFunc = Function()
noopFunc() // => undefined
like image 69
Dmitri Pavlutin Avatar answered Oct 05 '22 13:10

Dmitri Pavlutin


Here is another option.

5 Just an if check..

  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);
  }
);
like image 43
Keith Avatar answered Oct 05 '22 12:10

Keith