Sireesh Vattikuti
Sireesh Vattikuti

Reputation: 1190

How to write optional callback method in nodejs

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

Upvotes: 2

Views: 1382

Answers (3)

dcodesmith
dcodesmith

Reputation: 9614

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.
    }

}

Upvotes: 7

Menzo Wijmenga
Menzo Wijmenga

Reputation: 1121

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) {

})

Upvotes: 0

Andrey Popov
Andrey Popov

Reputation: 7510

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

Upvotes: 0

Related Questions