1

I usually write NodeJS code for hours, and there is a common situation I'm not sure how to face. Given the following async function call (where we forget the needed callback):

function foo (callback) {
    // Perform a task and call callback when finished
    callback();
}
foo(); // We forget the callback

Which is the better way to handle this? I find two options:

  1. Make foo() function more robust adding this as the first line: callback = callback || function () {}.
  2. Let it crash when foo() tries to call callback() and it does not exist.

Maybe a third option (which I prefer) would be the best one: throwing a custom error if the callback is not provided, as the first lines of foo(). For instance:

function foo (callback) {
    if (!callback) {
        throw new Error('No callback provided');
    }
    // More stuff here
    callback();
}

My question is: Is there any well-known patten to solve this situation? Which approach do you think is the better one? Do you solve this in a different way?

1
  • Are you tried to use Promises for async functions? It brings some new approaches for designing without callbacks. Commented Jul 11, 2014 at 9:21

1 Answer 1

4

It all depends if your callback is mandatory or not.

  • If it is mandatory then you should fail fast and do the throw new Error('No callback provided');.

  • If it is optional then the standard practice is that you just call it if it exists. Instead of creating a new function, just add a check in the place where it is gonna get called:

    if ( callback ) {
       callback();
    }
    

or in a single line:

callback && callback();
Sign up to request clarification or add additional context in comments.

2 Comments

Would typeof callback === "function" work better here?
@BenFortune if you have a variable called "callback", semantically places it as type function, I rather call it and have the code fail if it is not a function. That way it is easier to know that something wrong is being stored in the callback.

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.