简体   繁体   English

从nodejs的mongodb查询返回值

[英]Return value from a mongodb query from nodejs

EDIT 编辑

OK I read here ."You can't usefully return with asynchronous functions. You'll have to work with the result within the callback. This is due to the nature of asynchronous programming: "exit immediately, setting up a callback function to be called sometime in the future. 好的,我在这里读到。“您不能有用地返回异步函数。您将不得不在回调中处理结果。这是由于异步编程的特性:”立即退出,将回调函数设置为在将来的某个时间打来。 And, at least with the current standard of ECMAScript 5, you can't get around this. 而且,至少对于当前的ECMAScript 5标准,您无法解决这个问题。 As JavaScript is single-threaded, any attempt to wait for the callback will only lock up the single thread, keeping the callback and the return user forever pending in the event queue." 由于JavaScript是单线程的,因此任何等待回调的尝试都只会锁定单线程,从而使回调和返回用户永远保留在事件队列中。”

Is this still the case today? 今天还是这样吗?

ORIGINAL QUESTION 原始问题

I have a problem accessing my variable outside the function in my node.js application. 我在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

            })
        );

    });
}

I tried with async/await but I still have the same problem. 我尝试了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 }

I don't think you are going to be able to achieve what you are looking for. 我认为您无法实现所需的功能。 Async await only works once you are in scope of an async function. 仅当您处于异步功能范围内时,异步等待才有效。 Your top level calls are not inside an async function so you are forced to handle the returned Promise or callback. 您的顶级调用不在异步函数中,因此您被迫处理返回的Promise或回调。

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

Here are a couple of samples that are similar to what you want, but either way, the top level call into an async function will have to handle the response as a Promise. 这里有一些与您想要的示例类似的示例,但是无论哪种方式,对异步函数的顶级调用都必须将响应作为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", {});
}

It's important to understand that async await really isn't anything magical, behind the scenes it's translated to Promises really. 重要的是要了解,异步等待实际上并不是什么神奇的事情,在幕后它实际上已转换为Promises。 That's why your top level call into an async function can handle the response with a .then(). 这就是为什么您对异步函数的顶级调用可以使用.then()处理响应的原因。 It's just really much cleaner to read. 它真的很干净阅读。 The code above would roughly get translated and executed as: 上面的代码将大致翻译为:

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

getTypes doesn't return anything. getTypes不返回任何内容。 You've gotta pass it up If you're gonna use async/await try something like 您必须将其传递出去如果您要使用异步/等待,请尝试类似

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());

These might be helpful: How can I use asyn-await with mongoclient and how-to-use-mongodb-with-promises-in-node-js 这些可能会有所帮助: 如何与mongoclient一起使用asyn-await,以及如何在node-js中使用mongodb-promises-promises-

Also, you should probably close the connection with db.close() somewhere 另外,您可能应该在某处使用db.close()关闭连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM