简体   繁体   English

为什么我的异步mongodb查询函数挂起?

[英]Why is my asynch mongodb query function hanging?

First of all, please forgive me if this is a duplicate, I am new to coding and Javascript in general. 首先,如果这是重复的内容,请原谅我,我一般都不是编码和Javascript。

I have an async function that queries mongodb based on an objects passed in the function call. 我有一个异步函数,该函数根据函数调用中传递的对象来查询mongodb。 The function executes, and returns the results to a callback function which logs the results to the console, and then hangs. 该函数执行,然后将结果返回到回调函数,该回调函数将结果记录到控制台,然后挂起。 Ultimately, I want to take the results of the async query and then do something with them outside the original async function. 最终,我想获取异步查询的结果,然后在原始异步函数之外对它们执行某些操作。 I am not understanding why it hangs after it logs to the console. 我不明白为什么它登录到控制台后会挂起。

const MongoClient = require('mongodb').MongoClient;
let fObj = {
    field : {},
    limit : 100
}

let cObj = {
    dbName : 'myNewDatabase',
    colName : 'newCollection'
}

async function findDoc(cObj,fObj) {
    const url = 'mongodb://localhost:27017';
    const client = new MongoClient(url, { useNewUrlParser: true });
    try {
        await client.connect();
        const db = client.db(cObj.dbName);
        const col = db.collection(cObj.colName);
        console.log(`Connection Made to ${db.databaseName} database.`);
        return await col.find(fObj.field).limit(fObj.limit).toArray();
        client.close();
    } catch (err) {
        console.log(err.stack);
    }
};

findDoc(cObj,fObj).then(function(result) {
    console.log(result);
});

The code executes, and logs the results to the console, but then hangs. 该代码将执行,并将结果记录到控制台,然后挂起。 I have to ctrl-c out to get it to end. 我必须按ctrl-c结束它。 What am I missing? 我想念什么?

I suppouse you're running your code with NodeJs. 我支持您使用NodeJ运行代码。 This implies that you have a promise hanging up, which keeps the server running. 这意味着您有一个挂起的承诺,可以使服务器保持运行。 I assume this is because your connection to the DB is still open after you have found the document. 我认为这是因为找到文档后,您与数据库的连接仍处于打开状态。

You need to move your client.close(); 您需要移动client.close(); statement above the return statement, because it is never reached otherwise and your server will hang up forever. 语句位于return语句上方,因为否则将永远无法到达它,并且服务器将永远挂断。

Your code will look like this in the end: 最后,您的代码将如下所示:

const MongoClient = require('mongodb').MongoClient;
let fObj = {
    field : {},
    limit : 100
}

let cObj = {
    dbName : 'myNewDatabase',
    colName : 'newCollection'
}

async function findDoc(cObj,fObj) {
    const url = 'mongodb://localhost:27017';
    const client = new MongoClient(url, { useNewUrlParser: true });
    try {
        await client.connect();
        const db = client.db(cObj.dbName);
        const col = db.collection(cObj.colName);
        console.log(`Connection Made to ${db.databaseName} database.`);
        const result = await col.find(fObj.field).limit(fObj.limit).toArray();
        client.close();
        return result;
    } catch (err) {
        console.log(err.stack);
    }
};

findDoc(cObj,fObj).then(function(result) {
    console.log(result);
});

Also, I advise you to enclose your whole async function's body into the try clause. 另外,我建议您将整个异步函数的主体包含在try子句中。 This way you will be able to effectively intercept any error. 这样,您将能够有效地拦截任何错误。 Imagine your new MongoClient failed to instantiate - you would end up with an uncaught error inside a promise, which isn't very nice. 想象一下,您的new MongoClient无法实例化-您最终会在promise中遇到未捕获的错误,这不是很好。

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

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