1

I want to call this:

function fwc(a, b, callback) {

dosomestuff(a,b);
callback();
}

with this:

fwc (a,b);

Sometimes i need the callback and sometimes I don't. Can this cause trouble when I call the function and completely ignore the callback?

4 Answers 4

5

If you can't change the fwc function, you can call it like this :

fwc(a, b, function(){});

This way there won't be an error when fwc tries to call the third argument.

If you can change it, change it to

function fwc(a, b, callback) {
    dosomestuff(a,b);
    if (callback) callback();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the second approach is preferable over the first. Hopefully the OP can change the implementation of fwc
4

You should check the type of your callback like this:

function fwc(a, b, callback) {
 dosomestuff(a,b);
 if( typeof( callback ) == "function" ){
  callback();
 }
}

Comments

1

Use a ternary operator to do a simple check to see if the function exists.

function fwc(a, b, callback) {
    dosomestuff(a,b);
   (callback) ? callback():"";
}

Comments

1

Or like this:

function fwc(a, b, callback) {
    dosomestuff(a,b);
    callback && callback();
}

You can also check for callback type to make sure it's a function. If so check Travis's general answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.