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:
foo()
function more robust adding this as the first line: callback = callback || function () {}
callback = callback || function () {}
. 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 patter to solve this situation? Which approach do you think is the better one? Do you solve this in a different way?
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.