连接&& connection.close();

时间:2019-04-11 10:48:37

标签: node.js tedious

我正在使用Node.js和Tedious阅读一些代码,以创建一个连接到MS SQL Server的全栈应用程序。我偶然发现了这件作品。

function createRequest(query, connection) {
    var Request = require('tedious').Request;
    var req =
        new Request(query, 
                function (err, rowCount) {
                        if (err) {
                            console.trace(err);
                            throw err;
                        }
                        connection && connection.close();
                        console.log('Connection closed');
                });
    return req;
}

谁能解释一下这行 connection && connection.close(); 是吗?

2 个答案:

答案 0 :(得分:1)

connection && connection.close()实际上是一种我不推荐的“技巧”。

这是

if (connection) {
  connection.close()
}

技巧是使用&&运算符作为简写语法。如果左表达式是虚假的(例如undefinednull),那么右表达式甚至不会被求值。

您可以尝试使用

true && console.log('Hello')
// 
false && console.log('will never be logged')

There is a dedicated part about this short-circuit in the MDN documentation

答案 1 :(得分:0)

这就是说是否定义connection运行connection.close()

相同
if(connection){
    connection.close()
}

之所以有效,是因为&&返回第一个Falsy结果。

即:

console.log(false && 'something'); // false

console.log(true && 'something'); // 'something'
相关问题