简体   繁体   English

“ if(err)”在JavaScript中到底能进行哪些测试?

[英]What does 'if (err)' tests precisely in Javascript?

Many callback functions start by checking an err parameter as following: 许多回调函数通过检查err参数开始,如下所示:

function myCallback(err, result) {

    if ( err ) {

        // Handle error
        ...

    }

    ...

}

What does the if (err) test verifies? if (err)测试验证什么? Does it check whether the object is null ? 是否检查对象是否为null Does it check whether it is undefined ? 是否检查它是否undefined Shouldn't one test for instanceof Error ? 不应该为instanceof Error测试吗? When does this test return true ? 该测试何时返回true

In Node.js world, the callback functions have the following signature 在Node.js世界中,回调函数具有以下签名

function(error, result){}

If there is no error, then the error parameter is conventionally set to null , otherwise the corresponding error object. 如果没有错误,则通常将error参数设置为null ,否则将相应的错误对象设置为null

So, the check if (err) checks if we really have an error situation or not. 因此,检查if (err)是否检查我们是否确实存在错误情况。 If the err object is null , then the check will fail (since null is falsy) otherwise the error handling code is executed. 如果err对象为null ,则检查将失败(因为null为假),否则将执行错误处理代码。

Shouldn't one test for instanceof Error? 不应该为instanceof Error测试吗?

It is not necessarily an instance of Error object. 它不一定是Error对象的实例。 We can even pass an object literal as an error object or even an array representing array of errors. 我们甚至可以将对象文字作为错误对象或什至代表错误数组的数组传递。

Does it check whether the object is null? 是否检查对象是否为空? Does it check whether it is undefined? 是否检查它是否未定义?

The test will evaluate to be falsy is the error object is either null or undefined . 如果错误对象为nullundefined ,则测试将评估为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM