mongoose,express和node.js中的回调函数的参数
问题描述:
我遵循MCV方法来开发我的应用程序。我遇到一个问题,我不知道如何将参数传递给回调函数。mongoose,express和node.js中的回调函数的参数
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)
}
}
这里我的问题是:为什么在 “名单” 中的模型只是执行回调不传递任何论据?错误和动物究竟来自哪里?
我想我可能会错过一些与node.js和mongoose中的回调有关的概念。如果您能提供一些解释或指向某些材料,非常感谢。
答
函数列表想要传递一个回调函数。
所以你传递一个回调函数。
this.find().exec(cb)
也想要一个回调函数,所以我们通过我们从list
函数获得的回调。
的execute
函数然后调用回调(执行它)与参数err
和它接收到的,在这种情况下animals
的对象。
列表函数内部发生了类似return callback(err, objects)
的事情,最后调用回调函数。
您现在传递的回调函数有两个参数。这些是err
和animals
关键是:回调函数作为参数传递,但从未调用,直到它被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/
感谢您的回答。我了解你答案的第一部分。但是我对第二部分感到困惑:列表函数从未声明一个名为“animals”的变量。它如何将它从数据库收到的对象映射到“动物”? – LKS 2013-03-07 09:32:40
它不必知道对象的名称,它只是调用映射到'function(err,animals)'的'callback(err,objects)'。所以对象被映射到动物 – pfried 2013-03-07 09:34:07
也许你错过了那个回调被传递给列表函数,执行发生在列表函数内部,你看不到这里 – pfried 2013-03-07 09:45:37