为什么这两个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未定义”的错误。 这是怎么回事?

只要传递给函数的引用:

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

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

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