我能够在Node.js中向neDB数据库插入并检索数据。但是,我无法将检索到的数据传递到函数之外。我已经阅读了neDB文档,并尝试了不同回调和返回值的组合,但没有找到解决方案(参见下面的代码)。由于我对JavaScript还很新,所以不确定自己是否误解了变量的使用方式,或者这个问题与使用neDB有关,或者两者都有关系。请问有人能够解释一下为什么我的代码中的“x”永远不会包含来自数据库的JSON结果吗?我该怎么做才能让它工作呢?
var fs = require('fs'),
Datastore = require('nedb')
, db = new Datastore({ filename: 'datastore', autoload: true });
//generate data to add to datafile
var document = { Shift: "Late"
, StartTime: "4:00PM"
, EndTime: "12:00AM"
};
// add the generated data to datafile
db.insert(document, function (err, newDoc) {
});
//test to ensure that this search returns data
db.find({ }, function (err, docs) {
console.log(JSON.stringify(docs)); // logs all of the data in docs
});
//attempt to get a variable "x" that has all
//of the data from the datafile
var x = function(err, callback){
db.find({ }, function (err, docs) {
callback(docs);
});
};
console.log(x); //logs "[Function]"
var x = db.find({ }, function (err, docs) {
return docs;
});
console.log(x); //logs "undefined"
var x = db.find({ }, function (err, docs) {
});
console.log(x); //logs "undefined"*