为什么这两个 Mongoose 代码模式不等价?
Why aren't these two Mongoose code patterns equivalent?
以下代码模式有效:
collectionModel.findOne({"username" : username})
.exec()
.then(function (err, docs) { console.log(err); });
然而下面的(看似等价的)代码模式却没有:
var nameFunction = function (err, docs) {
console.log(err);
}
collectionModel.findOne({"username" : username})
.exec()
.then(nameFunction(err, docs));
的确,后一种代码模式会抛出“err
未定义”的错误。怎么回事?
只需将引用传递给函数:
collectionModel.findOne({"username" : username})
.exec()
.then(nameFunction);
您的代码正在调用 函数(或尝试调用),然后(如果尝试没有因错误而失败)将通过 return 值 到 .then()
.
函数引用本身就是对可以像任何其他值一样随意使用的函数的引用。当函数引用后跟带括号的参数列表时,即为函数调用。
以下代码模式有效:
collectionModel.findOne({"username" : username})
.exec()
.then(function (err, docs) { console.log(err); });
然而下面的(看似等价的)代码模式却没有:
var nameFunction = function (err, docs) {
console.log(err);
}
collectionModel.findOne({"username" : username})
.exec()
.then(nameFunction(err, docs));
的确,后一种代码模式会抛出“err
未定义”的错误。怎么回事?
只需将引用传递给函数:
collectionModel.findOne({"username" : username})
.exec()
.then(nameFunction);
您的代码正在调用 函数(或尝试调用),然后(如果尝试没有因错误而失败)将通过 return 值 到 .then()
.
函数引用本身就是对可以像任何其他值一样随意使用的函数的引用。当函数引用后跟带括号的参数列表时,即为函数调用。