将node.js的neDB数据存入变量

8
我能够在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"*
3个回答

6

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

在你的例子中,以下方法可以解决:

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

console.log(x);

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
}

编辑

这篇博客文章讲述了关于异步编程的知识,并且还有很多相关资源可以供您查阅。

这个库是一个在Node中帮助处理异步流程控制的受欢迎的工具。

P.S.
希望这能有所帮助。如果您需要澄清什么,请尽管问我 :)


0

我不得不学习一些关于异步函数的知识才能正确地使用它。对于那些正在寻找有关从nedb获取返回值的具体帮助的人,这是我成功使用的代码片段。我在electron中使用它。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接