函数返回值在nodejs中未定义

Luc*_*kyy 4 callback mongodb node.js

我是第一次在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); }); 
Run Code Online (Sandbox Code Playgroud)

此函数从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 });
};
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

谢谢和问候,Luckyy.

Aus*_*eco 5

您需要在数据库请求完成后呈现此...因此需要在回调中调用它.

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

它是异步的,所以你不能只按顺序放置值,需要经历回调.