函数返回的值在nodejs中未定义

我正在第一次在NodeJs项目上工作。 而现在我坚持通过JS的函数返回值,并得到值使用快递。

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中完美地检索值并写入控制台。 但我需要的是使用检索的价值发送到这个函数的快速HTML文件通过“returnedData”

 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 }); }; 

任何帮助,将不胜感激。

感谢和问候,幸运。

你需要在数据库请求完成后渲染它。所以需要从callback中调用它。

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

它是asynchronous的,所以你不能只是把价值观,需要通过callback。