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:
- Make
foo()function more robust adding this as the first line:callback = callback || function () {}. - Let it crash when
foo()tries to callcallback()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?