我遵循 MCV 方法来开发我的应用程序。我遇到一个问题,我不知道如何将参数传递给回调函数。
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( 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)
}
}
我的问题来了:为什么模型中的“列表”可以不传递任何参数就执行回调?错误和动物究竟从何而来?
我想我可能会遗漏一些node.js和mongoose中回调相关的概念。如果您能提供一些解释或指出一些 Material ,非常感谢。
最佳答案
函数列表要传递一个回调函数。
所以你传递了一个回调函数。
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);
}
});
可以在这里找到 fiddle :http://jsfiddle.net/yJWmy/
关于javascript - mongoose、express 和 node.js 中回调函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15266162/