Reputation: 234
I would like to know your opinion about below solution. In node.js I often see error handling this way:
async.each(context.areas, capacityOfArea, function(error) {
if (error) {
next(error);
} else {
next();
}
});
It's often OK, but sometimes it obscures the code (in my opinion) and I would like to simplify this. Does below code equal?
async.each(context.areas, capacityOfArea, function(error) {
next(error||undefined);
});
Upvotes: 0
Views: 166
Reputation: 816364
They could be the same, depending on how next
is handling its arguments. But technically they are not the same. In the first case, you are not passing an argument at all, so inside next
, arguments.length
will be 0
. In the second case, you are always passing an argument, so arguments.length
will be 1
.
Again: Whether or not both produce the same behavior depends on the implementation of next
. Most likely yes.
Probably the best way to write this code would be
async.each(context.areas, capacityOfArea, next);
Upvotes: 2
Reputation: 3055
Yes, they are the same. Think about what the caller sees -- would next() be able to distinguish next() from next(undefined)?
But taking it one step further, all async cares is whether the error is truthy, it accepts undefined or false or null as success indicators too. And error will either be truthy (an error), or not truthy. If not truthy, we want to call next(<not truthy>), and if error, we want to call next(error), which leads to
async.each(context.areas, capacityOfArea, function(error) {
next(error);
}
Upvotes: 2