3

我遵循 MCV 方法来开发我的应用程序。我遇到一个问题,我不知道参数是如何传递给回调函数的。

动物.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)

动物.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)
    }
}

我的问题来了:为什么模型中的“列表”可以只执行回调而不传递任何参数?错误和动物实际上来自哪里?

我想我可能会错过一些与 node.js 和 mongoose 中的回调相关的概念。如果您能提供一些解释或指出一些材料,非常感谢。

4

1 回答 1

2

函数列表想要传递一个回调函数。

所以你传递一个回调函数。

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

然后该函数使用参数和它接收到的对象execute调用回调(执行它) ,在本例中为.erranimals

在列表函数内部发生了一些类似于return callback(err, objects)最终调用回调函数的事情。

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

关键是:回调函数作为参数传递,但在被exec. err该函数使用映射到和的参数调用它animals

编辑:

由于接缝不清楚,我将做一个简短的示例:

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/

于 2013-03-07T09:26:59.223 回答