Arguments to callback function in mongoose, express and node.js

有些话、适合烂在心里 提交于 2020-01-01 16:24:08

问题


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.


回答1:


The function list wants to have a callback function passed.

So you pass a callback function.

this.find().exec(cb) wants a callback function too, so we pass the callback we got from the list function.

The execute function then calls the callback (executes it) with the parameters err and the object it received, in this case animals.

Inside of the list function happens something like return callback(err, objects) what is finally calling the callback function.

The callback function you passed now has got two parameters. These are err and animals

The key is : The callback function is passed as a parameter, but is never called until it is called by the exec. This function is calling it with parameters which are mapped to err and animals

EDIT:

As it seams unclear i will do a short example:

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

Can be found as a fiddle here : http://jsfiddle.net/yJWmy/



来源:https://stackoverflow.com/questions/15266162/arguments-to-callback-function-in-mongoose-express-and-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!