4

When using a 3rd party library I often find an optional parameter in the callback.

For example, in Mocha when the callback done parameter exists, it waits for done to be invoked before moving on to another test case.

someFunction(function(done) { /** code **/ })
someFunction(function() { /** this behaves differently than above **/ })

How can I achieve the same behavior?

melpomene
  • 84,125
  • 8
  • 85
  • 148
otong
  • 1,387
  • 2
  • 17
  • 28
  • Important points regarding ES2015 added features: https://stackoverflow.com/a/41171439/3702797 – Kaiido Jun 24 '19 at 06:57
  • "*How can I achieve the same behavior?*" - Don't. Write two functions instead, `someFunction` and `someFunctionAsync`. Or even better, don't pass `done` callbacks but expect a promise to be returned, and always just use `Promise.resolve(callback())` which also works when nothing is returned. – Bergi Jun 24 '19 at 07:39

1 Answers1

3

You can check the length attribute of the function object

console.log((()=>42).length);    // 0
console.log(((x,y)=>42).length); // 2

note however that you cannot be sure of exactly how many the function is going to access, because it's also possible to use arguments inside Javascript non-arrow functions and "rest" parameters inside arrows (that are not counted in .length attribute).

6502
  • 112,025
  • 15
  • 165
  • 265