3

I follow a MCV approach to develop my application. I encounter a problem that I dont know how the arguments are passed to the callback function.

animal.js (model)

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 (controller)

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)
    }
}

Here comes my question: Why can the "list" in the model just execute callback without passing any argument? Where do the err and animals come from actually?

I think I may miss some concepts related to callback in node.js and mongoose. Thanks a lot if you can provide some explanation or point me to some materials.

4

1 に答える 1

2

関数リストには、コールバック関数が渡される必要があります。

したがって、コールバック関数を渡します。

this.find().exec(cb)コールバック関数も必要なので、list関数から取得したコールバックを渡します。

次に、関数は、受け取ったパラメーターとオブジェクト (この場合はexecute) を使用してコールバックを呼び出します (実行します) 。erranimals

リスト関数の内部では、return callback(err, objects)最終的にコールバック関数を呼び出しているようなことが起こります。

渡したコールバック関数には 2 つのパラメーターがあります。これらは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/

于 2013-03-07T09:26:59.223 に答える