2

I have function, In some cases i need to use the callback to proceed further and in some cases i don't even need to bother about callback.

Please suggest me how to write a function with optional callback

Thanks in Advance

Sireesh Vattikuti
  • 1,180
  • 1
  • 9
  • 21

3 Answers3

7

You need something like this. It's a common practice. You can check if the callback parameter exists first and that it is in fact a function.

function doSomething (argA, callback) {

    // do something here

    if (callback && typeof callback === 'function') {
        callback();
        // do some other stuff here if callback exists.
    }

}
Lioness100
  • 8,260
  • 6
  • 18
  • 49
dcodesmith
  • 9,590
  • 4
  • 36
  • 40
0

JavaScript is so called "duck typing" language, which in your means there are not hard limitations on method parameters. All these are gonna be fine:

function test() {
    console.log(arguments); // [1, 2, 3], Array style
    console.log(param1); // undefined
    console.log(param2); // undefined
}

function test(param1) {
    console.log(arguments); // [1, 2, 3], Array style
    console.log(param1); // 1
    console.log(param2); // undefined
}

function test(param1, param2) {
    console.log(arguments); // [1, 2, 3], Array style
    console.log(param1); // 1
    console.log(param2); // 2
}

test(1, 2, 3);

You can even call with different kind of params:

test();
test(1, 2);
test(1, 2, 3, 4, 5);

So as long as you keep track of how much you actually need, you can provide them in method definition. If some of them are optional, you have two options:

  1. Define but not use them
    • this is commonly used when the length of the arguments is small
  2. Use arguments in order to get the rest of the args
Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
0

I know this is a old post, but I didn't see this solution which I think is more clean.

Callback will only be called if it is a instance of function (thus callable).

function example(foo, callback) {
    // function logic

    (callback instanceof Function) && callback(true, data)
}

example('bar')
example('bar', function complete(success, data) {

})
Menzo Wijmenga
  • 1,011
  • 6
  • 13
  • You shouldn't use instanceof in a condition. Look here https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used#comment38883772_6625960 – Faizan Anwer Ali Rupani Mar 18 '19 at 15:01