Node.js 在mongonodejs中使用wait调用构造函数和使用new调用构造函数有什么区别?
这两者有什么区别Node.js 在mongonodejs中使用wait调用构造函数和使用new调用构造函数有什么区别?,node.js,mongodb,driver,Node.js,Mongodb,Driver,这两者有什么区别 从“mongodb”导入{MongoClient} 异步函数run(){ 试一试{ const client=wait MongoClient('mongodb://localhost:27017/testing“,{useNewUrlParser:true,useUnifiedTopology:true}).connect() //其他代码 }最后{ 等待客户端关闭() } } run().catch(错误=>{console.error(错误)}) 这是: 从“mongo
从“mongodb”导入{MongoClient}
异步函数run(){
试一试{
const client=wait MongoClient('mongodb://localhost:27017/testing“,{useNewUrlParser:true,useUnifiedTopology:true}).connect()
//其他代码
}最后{
等待客户端关闭()
}
}
run().catch(错误=>{console.error(错误)})
这是:
从“mongodb”导入{MongoClient}
异步函数run(){
const client=new MongoClient('mongodb://localhost:27017/testing“,{useNewUrlParser:true,useUnifiedTopology:true})
试一试{
等待client.connect()
//其他代码
}最后{
等待客户端关闭()
}
}
run().catch(错误=>{console.error(错误)})
文档摘要显示,第二种方法是创建客户机,但我经常发现第一种方法要使用第一种方法将客户机的构造置于try块之下。这有两个作用:
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)
您可以通过连接到不正确的端口来测试这一点。您在
上使用wait
。connect()
在这两种情况下都使用,而不是在构造函数上。