javascript - mongoose、express 和 node.js 中回调函数的参数

标签 javascript node.js callback express mongoose

我遵循 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) 的事情最终调用了回调函数。

您现在传递的回调函数有两个参数。这些是 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);
    }
});

可以在这里找到 fiddle :http://jsfiddle.net/yJWmy/

关于javascript - mongoose、express 和 node.js 中回调函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15266162/

相关文章:

javascript - 按空格键按整页水平滚动

javascript - Extjs 4、事件处理、范围、自定义组件

javascript - 将确认/取消弹出窗口插入 JQuery - CSS 问题

node.js - 如何构建自己的 MeanJS Docker 镜像?

javascript - 为什么 Nodejs callback() 不能访问回调范围外的变量?

iOS Swift : Closures (Callbacks) versus Delegates, 什么时候使用哪个?

javascript - 在所有有没有 GuildID (Discord.js v12) 的机器人的服务器中使用斜杠命令

node.js - 调试Electron应用程序: Breakpoints not working (“Breakpoint ignored because generated code not found” )

node.js - 如何找到对 npm 包的反向依赖?

javascript - 如何将两个单独的查询传递给 promise 链末尾的回调函数?