我正在阅读一些使用Node.js和繁琐的代码来创建连接到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();这行是做什么的?
发布于 2019-04-11 18:54:30
connection && connection.close()实际上是我不推荐的一种“技巧”。
这意味着
if (connection) {
connection.close()
}诀窍是使用&&运算符作为一种简写语法。如果左边的表达式是假的(例如undefined或null ),那么右边的表达式甚至不会被求值。
您可以使用以下命令进行尝试
true && console.log('Hello')
//
false && console.log('will never be logged')There is a dedicated part about this short-circuit in the MDN documentation
发布于 2019-04-11 18:55:05
与以下内容相同
if(connection){
connection.close()
}它之所以有效,是因为&&返回第一个Falsy结果。
即:
console.log(false && 'something'); // false
console.log(true && 'something'); // 'something'https://stackoverflow.com/questions/55630679
复制相似问题