mongoose、express和node.js中回调函数的参数

3

我采用MVC开发应用程序。我遇到一个问题,就是不知道参数如何传递给回调函数。

animal.js(模型)

var mongoose = require('mongoose')
, Schema = mongoose.Schema

var animalSchema = new Schema({ name: String, type: String });
animalSchema.statics = {
     list: function(cb) {
         this.find().exec(cb)
     }
}
mongoose.model('Animal', animalSchema)

animals.js (控制器)

var mongoose = require('mongoose')
, Animal = mongoose.model('Animal')

exports.index = function(req, res) {
    Animal.list(function(err, animals) {
        if (err) return res.render('500')
        console.log(animals)
    }
}

这里是我的问题:为什么模型中的“list”只能执行回调而不传递任何参数?实际上,err和animals来自哪里?
我认为我可能错过了与node.js和mongoose中回调相关的一些概念。如果您可以提供一些解释或指向一些资料,非常感谢。
1个回答

2

函数列表希望传递回调函数。

因此,您传递一个回调函数。

this.find().exec(cb) 还想要一个回调函数,所以我们传递从list函数得到的回调函数。

然后 execute 函数使用参数 err 和它接收到的对象(在这种情况下为animals)来调用回调函数(执行它)。

在 list 函数内部发生了类似于 return callback(err, objects) 的操作,最终调用回调函数。

您传递的回调函数现在有两个参数。这些是 erranimals

关键是:回调函数作为参数传递,但在exec调用它之前不会被调用。该函数在调用时带有映射到erranimals的参数。

编辑:

由于似乎不太清楚,我将做一个简短的例子:

var exec = function (callback) {
    // Here happens a asynchronous query (not in this case, but a database would be)
    var error = null;
    var result = "I am an elephant from the database";
    return callback(error, result);
};

var link = function (callback) {
    // Passing the callback to another function 
    exec(callback);
};

link(function (err, animals) {
    if (!err) {
        alert(animals);
    }
});

可以在这里找到一个演示:http://jsfiddle.net/yJWmy/


谢谢您的回答。我理解了您回答的第一部分。但是我对第二部分感到困惑:list函数从未声明名为“animals”的变量。它如何将从数据库接收到的对象映射到“animals”? - LKS
它不需要知道对象的名称,只需调用callback(err, objects),该函数映射到function (err, animals)。因此,objects被映射到animals。 - pfried
也许你错过了回调函数也被传递给了列表函数,执行发生在列表函数内部,你在这里看不到。 - pfried
我这样想是正确的吗?:当 "animal.js" 中的 "list" 函数运行此行 this.find().exec(cb) 时,this.find() 返回两个变量 "err" 和 "objects" 并调用 cb(err, objects)。因此它映射到 function(XXX, YYY),在这种情况下是 function(err, animals) - LKS
这让我感到困惑,因为从mongoose的API文档Mongoose exec API中,并没有提到errobjects是如何传递给回调函数的。 - LKS
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接