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

我已经阅读了neDB文档,并搜索并尝试了回调和返回的不同组合(请参见下面的代码),但没有找到解决方案。

我是javascript的新手,所以我不知道我是否误解了一般如何使用变量,或者这个问题是否与专门使用neDB有关,或者两者都不相关。

有人可以解释一下为什么我的代码中的“x”不包含数据库中的docs 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"*

最佳答案

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

当您调用异步函数时,将继续执行程序,并传递“var x = what”语句。对变量的赋值,无论收到任何回调的结果,您都需要在回调本身内部执行...您需要的是...

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
}

编辑

Here是有关异步编程的不错的博客文章。您可以从中获取有关此主题的更多资源。

This是一个流行的库,可帮助 Node 进行异步流控制。

P.S.
希望这可以帮助。请一定要问您是否需要澄清的东西:)

10-05 20:46
查看更多