簡體   English   中英

mongoose,express和node.js中回調函數的參數

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

我遵循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(控制器)

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)內容,最終調用回調函數。

您現在傳遞的回調函數有兩個參數。 這些是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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM