【发布时间】:2019-10-26 03:15:38
【问题描述】:
我尝试打包数据库连接以获得更多可重用性。 我想达到这样的目标:
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
const db = client.db(dbName);
// do something...
client.close();
})
.catch(err=>console.log(err));
因此,我可以在其他地方使用它:
//For example
//query
mongoPromise.then((db)=>db.collection('user').find().toArray())
//insert
mongoPromise.then((db)=>db.collection('test').insert({...}))
查询或插入完成后,MongoClient 将关闭
第一种方法,我可以通过混合回调和承诺来找出解决方案。
callback和promise混在一起不好吗?
// First method
const mongoPromiseCallback =(callback)=>MongoClient.connect(url,{ useNewUrlParser: true })
.then(async(client)=>{
const db = client.db(dbName);
await callback(db);
console.log("close the client");
client.close();
})
.catch(err=>console.log(err))
mongoPromiseCallback(db=>db.collection('user').find().toArray())
.then(res=>console.log(res)));
在另一种方法中,我尝试仅使用承诺,但我不知道
我在哪里可以关闭客户端。
// the other method
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
const db = client.db(dbName);
return new Promise(function(resolve, reject) {
resolve(db);
});
})
.catch(err=>console.log(err));
mongoPromise.then(db=>db.collection('user').find().toArray())
.then(res=>console.log("res"));
【问题讨论】:
标签: javascript node.js mongodb promise callback