我第一次从事 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 });
};
任何帮助,将不胜感激。
谢谢和问候,幸运。