【问题标题】:function returning values as undefined in nodejs函数返回值在nodejs中未定义
【发布时间】:2012-09-11 04:23:27
【问题描述】:

我是第一次从事 NodeJs 项目。现在我被困在函数通过 JS 返回值并获取值以在 express 中使用。

var dbitems = "before fn";
function refreshData(callback) {
        db.open(function (err, db) {
            if (!err) {
                db.collection('emp').find().toArray(function (err, items) {
                    dbitems = items;
                    callback(JSON.stringify(items));
                });
            }
            else {
                console.log("Could not be connnected" + err);
                dbitems = {"value":"not found"};
            }
        });

    }
}


refreshData(function (id) { console.log(id); }); 

此函数从 refreshData 中完美检索值并写入控制台。但我需要的是使用检索到的值通过“returnedData”从这个函数发送到 express html 文件

exports.index = function (req, res) {
    var valrs = refreshData(function (id) {
        console.log(JSON.parse(id)); ---this again writes data perfectly in the console
    });
    console.log(valrs); -------------------but again resulting in undefined
    res.render('index', { title: 'Express test', returnedData: valrs });
};

任何帮助将不胜感激。

感谢和问候, 幸运。

【问题讨论】:

    标签: node.js mongodb callback


    【解决方案1】:

    您需要在数据库请求完成后呈现它。所以它需要从回调中调用。

    exports.index = function (req, res) {
        refreshData(function (id) {
            res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
        });
    };
    

    它是异步的,所以你不能只是按顺序排列值,需要通过回调。

    【讨论】:

    • 好了,谢谢 Agreco。中肯的回答,非常感谢。
    猜你喜欢
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2020-01-31
    • 2019-03-24
    • 2019-02-25
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多