简体   繁体   English

MongoDB 客户端使用异步/等待连接使 function 卡住

[英]MongoDB client connect using async/await makes function stuck

MongoDB client connect seems to work but the function just hangs. MongoDB 客户端连接似乎工作,但 function 只是挂起。

app.js应用程序.js

async function test() {
  console.log('Hello world');
  await new Promise((resolve) => {
    setTimeout(resolve, 50);
  });
  console.log('Bye world');
}
test();

When I run using node app.js on cmd, I get the logs and the shell exits as expected.当我在 cmd 上使用 node app.js 运行时,我得到了日志,并且 shell 按预期退出。 However, when I run this code ->但是,当我运行此代码时->

async function test() {
  console.log('Hello world');
  await MongoClient.connect(MONGODB_URI);
  console.log('Bye world');
}
test();

and I run again using node app.js.我使用节点 app.js 再次运行。 This time also I get both the logs but the process never exits.这次我也得到了两个日志,但进程永远不会退出。 What is happening here?这里发生了什么? Am I missing something very obvious?我错过了一些非常明显的东西吗?

I did figure out what is happening here.我确实弄清楚这里发生了什么。

const client = await MongoClient.connect(URI);

returns a connected client to the database.将连接的客户端返回到数据库。 However, if I don't close the connection to the client, the node process remains hanging.但是,如果我不关闭与客户端的连接,则节点进程仍然挂起。 So, the code below works as expected.因此,下面的代码按预期工作。

const client = await MongoClient.connect(URI);
// Execute some queries
await client.close();

Although it might simply be a mistake of me not reading the MongoDB documentation correctly, I'll share the consequence of this error that I was facing.尽管我没有正确阅读 MongoDB 文档可能只是一个错误,但我将分享我所面临的这个错误的后果。

I had an AWS lambda function code as below:我有一个 AWS lambda function 代码如下:

module.exports.handler = async (event) => {
  const client = await MongoClient.connect(URI);

  // Do something with the client but forgets to close

  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify({ foo: 'bar' }),
  };

  console.log(response);
  return response;
};

I get the log of the response being printed out but the function will timeout and will not return the response.我得到了正在打印的响应日志,但是 function 将超时并且不会返回响应。

I pulled some of my hair as it was my first time working with lambdas and MongoDB so remember folks, close your connection after you're done with them.我拉了一些头发,因为这是我第一次使用 lambdas 和 MongoDB 所以记住伙计们,在你完成它们之后关闭你的连接。

Hope this helps someone.希望这可以帮助某人。

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

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