【发布时间】: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,而不是在构造函数上。