以下代码模式有效:
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
未定义"。发生了什么事?
答案 0 :(得分:2)
只需将参考传递给函数:
collectionModel.findOne({"username" : username})
.exec()
.then(nameFunction);
你的代码调用函数(或尝试),然后(如果尝试没有失败并出现错误)将传递返回值到.then()
。
函数引用本身是对函数的引用,可以像任何其他值一样被抛出。当函数引用后跟带括号的参数列表时,该函数调用。