【问题标题】:Return value from a mongodb query from nodejs从 nodejs 的 mongodb 查询返回值
【发布时间】:2019-08-22 22:26:04
【问题描述】:

编辑

好的,我读到了here。“您不能使用异步函数有效地返回。您必须在回调中处理结果。这是由于异步编程的性质:“立即退出,设置将来某个时候调用的回调函数。而且,至少对于当前的 ECMAScript 5 标准,您无法绕过这个问题。由于 JavaScript 是单线程的,任何等待回调的尝试都只会锁定单线程,从而使回调和返回用户永远在事件队列中等待。”

今天还是这样吗?

原始问题

在我的 node.js 应用程序的函数之外访问我的变量时遇到问题。

const url = "mongodb://localhost:27017/";
getAllSampleTypes();

// I would like to have the variable "requested" accessible here

function getAllSampleTypes() {
    MongoClient.connect(url, function (err, db) {
        var dbo = db.db("myDb");
        dbo.collection("data").distinct("sample_type", {}, (function (err, requested) {
// variable "requested" is accessible here

            })
        );

    });
}

我尝试了 async/await 但我仍然遇到同样的问题。

function getTypes() {
    MongoClient.connect(url, async function (err, db) {
        let dbo = db.db("myDb");
        return await dbo.collection("data").distinct("sample_type", {});

    });
}
console.log(getTypes()); //Promise { undefined }

【问题讨论】:

  • 有趣。我想知道这是否是与this 相关的问题。
  • getTypes() 不返回任何内容
  • @Andreas 你知道我该如何解决这个问题吗?
  • 你尝试混合同步和异步函数
  • 使用异步或回调

标签: javascript node.js mongodb scope


【解决方案1】:

我不认为你将能够实现你正在寻找的东西。异步等待仅在您处于异步函数的范围内时才起作用。您的顶级调用不在异步函数内,因此您必须处理返回的 Promise 或回调。

例如getAllSampleTypes().then(function(response){});

这里有几个与您想要的类似的示例,但无论哪种方式,对异步函数的顶级调用都必须将响应作为 Promise 来处理。

const url = "mongodb://localhost:27017/";

getAllSampleTypes().then(function(sample_types){
    // Do something here.
});


async function getAllSampleTypes() {
    var db = await mongo.connect(url);
    var dbo = db.db("myDb");
    return await dbo.collection("data").distinct("sample_type", {});
}

重要的是要理解 async await 真的不是什么神奇的东西,在幕后它确实被转换为 Promises。这就是为什么您对异步函数的顶级调用可以使用 .then() 处理响应。读起来真的干净多了。上面的代码大致会被翻译和执行为:

const url = "mongodb://localhost:27017/";

getAllSampleTypes().then(function(sample_types){
    // Do something here.
});

function getAllSampleTypes() {
    return new Promise(function(resolve, reject){ 
        mongo.connect(url).then(function(db){
            var dbo = db.db("myDb");
            dbo.collection("data").distinct("sample_type", {}).then(function(results) {
                resolve(results);
            });
        });
    });
}

【讨论】:

  • 非常感谢,非常有帮助。
【解决方案2】:

getTypes 不返回任何内容。你必须放弃它 如果你要使用 async/await 试试类似的东西

async function getTypes() {
  const db = MongoClient.connect(url);
  const dbo = db.db("myDb");
  return await dbo.collection("data").distinct("sample_type", {});
}
console.log(await getTypes());

这些可能会有所帮助: How can I use asyn-await with mongoclienthow-to-use-mongodb-with-promises-in-node-js

另外,您可能应该在某处关闭与 db.close() 的连接

【讨论】:

  • 好的,谢谢。我会检查这些链接。我试过你的建议,但没有奏效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 2013-05-15
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多