将node.js neDB数据获取到一个variables中

我能够在nodejs中从neDB数据库插入和检索数据。 但是我不能将数据传递到检索​​它的函数之外。

我已经通读了neDB文档,并且search了并且尝试了不同的callback和返回组合(见下面的代码),而没有find解决scheme。

我是新来的JavaScript,所以我不知道如果我误解如何使用一般的variables,或者如果这个问题是有关使用专门或两者的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"* 

callback在JavaScript中通常是asynchronous的,这意味着你不能使用赋值操作符,因此你不会从callback函数中返回任何东西。

当你调用一个asynchronous函数执行你的程序时,传递'var x = whatever'语句。 赋值给一个variables,接收到的任何callback的结果,你需要从callback本身执行…你需要的东西在行…

 var x = null; db.find({ }, function (err, docs) { x = docs; do_something_when_you_get_your_result(); }); function do_something_when_you_get_your_result() { console.log(x); // x have docs now } 

编辑

这里是一个关于asynchronous编程的好博客文章。 这个话题还有更多的资源可供select。

这是一个stream行的库,以帮助节点的asynchronousstream量控制。

PS
希望这可以帮助。 请通过一切方式询问是否需要澄清一些事情:)

我不得不学习一些关于asynchronous函数的知识。 对于那些正在寻求从nedb获得返回值的特定帮助的人来说,这里有一段对我有用的东西。 我正在用电子。

 function findUser(searchParams,callBackFn) { db.find({}, function (err, docs)) { //executes the callback callBackFn(docs) }; } usage findUser('John Doe',/*this is the callback -> */function(users){ for(i = 0; i < users.length; i++){ //the data will be here now //eg users.phone will display the user's phone number }})