将node.js neDB数据转换为变量

cur*_*ips 7 javascript node.js

我能够在nodejs中插入和检索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"*
Run Code Online (Sandbox Code Playgroud)

Dmi*_*eev 6

回调在JavaScript中通常是异步的,这意味着您不能使用赋值运算符,因此您不会从回调函数返回任何内容.

当你调用一个异步函数执行你的程序继续时,传递'var x = whatever'语句.对变量的赋值,收到任何回调的结果,你需要在回调本身内执行......你需要的东西是......

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
}
Run Code Online (Sandbox Code Playgroud)

编辑

是一篇关于异步编程的好文章.您可以在这个主题上获得更多资源.

是一个流行的库,可以帮助节点的异步流控制.

PS
希望这会有所帮助.请务必询问您是否需要澄清一些内容:)


小智 5

我遇到了同样的问题。最后,我使用了 async-await 和带有 resolve 的 promise 之间的组合来解决它。

在您的示例中,以下内容将起作用:

var x = new Promise((resolve,reject) {
    db.find({ }, function (err, docs) {
        resolve(docs);
    });
});

console.log(x);
Run Code Online (Sandbox Code Playgroud)