【问题标题】:What is the difference between calling the constructor with await and calling it with new in Mongo nodejs?在 Mongo nodejs 中使用 await 调用构造函数和使用 new 调用构造函数有什么区别?
【发布时间】:2021-07-04 03:51:06
【问题描述】:

这两者有什么区别?

import { MongoClient } from 'mongodb'
async function run() {
  try {
    const client = await MongoClient('mongodb://localhost:27017/testing', { useNewUrlParser: true, useUnifiedTopology: true }).connect()
    // other code
  } finally {
    await client.close()
  }
}
run().catch(error => { console.error(error) })

还有这个:

import { MongoClient } from 'mongodb'

async function run() {
  const client = new MongoClient('mongodb://localhost:27017/testing', { useNewUrlParser: true, useUnifiedTopology: true })
  try {
    await client.connect()
    // other code
  } finally {
    await client.close()
  }
}
run().catch(error => { console.error(error) })

文档显示第二个是创建客户端的official way,但我经常发现第一个被使用

【问题讨论】:

  • 你在这两种情况下都在.connect()上使用await,而不是在构造函数上。

标签: node.js mongodb driver


【解决方案1】:

第一种用法将客户端的构造置于 try 块之下。这做了两件事:

  1. 构造函数抛出的任何异常都将由 catch 块处理。
  2. 客户端对象的作用域是 try 块,在 catch 块中不可用。

这样做最明显的后果是,catch 块中的清理永远不会起作用,因为那里没有定义客户端:

risque% node test.js
ReferenceError: client is not defined
    at run (/home/w/apps/tests/node-try-ctor/test.js:10:5)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)

您可以通过连接到错误的端口来进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多