使用NodeJS,MongoDb。
MongoClient返回一个非常好的承诺,但我不确定我是否正确使用它。做什么最干净的方法是什么:
const mongo = require('mongodb').MongoClient;
return mongo
.connect(getConnectionString())
.then(con => {
func1(con)
.then(val => {return func2(con, val);})
.then(val => {con.close(); return val;})
.catch(err => log.error(err));
});
//contrived func to get my point across
func1(connection) {
//use connection to fetch data
return fetchedData;
}
//contrived func to get my point across
func2(connection, val) {
//use connection to fetch data
return fetchedData + val;
}
你看我是如何为连接创建一个范围的,这样我就可以用func1& amp;来关闭它。 func2完成了。有更清洁的方法吗?
如果有更简洁的方式来调用func1& funct2我也很感激。
答案 0 :(得分:0)
我会使用Bluebird的.using
直接来自其API文档的示例
using(getConnection(), function(connection) {
// Don't leak the `connection` variable anywhere from here
// it is only guaranteed to be open while the promise returned from
// this callback is still pending
return connection.queryAsync("SELECT * FROM TABLE");
// Code that is chained from the promise created in the line above
// still has access to `connection`
}).then(function(rows) {
// The connection has been closed by now
console.log(rows);
});