为什么这两个Mongoose代码模式不等同?

时间:2015-04-09 16:22:58

标签: javascript node.js mongoose

以下代码模式有效:

   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未定义"。发生了什么事?

1 个答案:

答案 0 :(得分:2)

只需将参考传递给函数:

collectionModel.findOne({"username" : username})
               .exec()
               .then(nameFunction);

你的代码调用函数(或尝试),然后(如果尝试没有失败并出现错误)将传递返回值.then()

函数引用本身是对函数的引用,可以像任何其他值一样被抛出。当函数引用后跟带括号的参数列表时,该函数调用。

相关问题