[英]JavaScript: handling undefined as parameter - are those solutions equal?
I would like to know your opinion about below solution. 我想知道您对以下解决方案的意见。 In node.js I often see error handling this way: 在node.js中,我经常看到这种错误处理方式:
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);
});
Yes, they are the same. 是的,它们是相同的。 Think about what the caller sees -- would next() be able to distinguish next() from next(undefined)? 想一想调用者看到的内容-next()能够区分next()和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. 但是更进一步,所有异步操作都关心错误是否为真,它也接受未定义或错误或null作为成功指示符。 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 如果不正确,则要调用next(<not truey>),如果错误,则要调用next(error),这将导致
async.each(context.areas, capacityOfArea, function(error) {
next(error);
}
They could be the same, depending on how next
is handling its arguments. 它们可能是相同的,具体取决于next
如何处理其参数。 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
. 在第一种情况下,您根本没有传递参数,因此在next
内部, arguments.length
将为0
。 In the second case, you are always passing an argument, so arguments.length
will be 1
. 在第二种情况下,您总是传递一个参数,因此arguments.length
将为1
。
Again: Whether or not both produce the same behavior depends on the implementation of next
. 同样:两者是否产生相同的行为取决于next
的实现。 Most likely yes. 很有可能。
Probably the best way to write this code would be 也许编写此代码的最佳方法是
async.each(context.areas, capacityOfArea, next);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.