[英]What is the cleanest way to close promised connection in javascript
Using NodeJS, MongoDb. 使用NodeJS,MongoDb。
MongoClient returns a promise which is really nice, but I am not sure if I am using it correctly. MongoClient返回一个非常好的承诺,但是我不确定我是否正确使用了它。 What is the cleanest way to do something like: 做这样的最干净的方法是什么:
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;
}
You see how I have create a scope for the connection so that I can close it with func1 & func2 are done. 您将看到我如何为连接创建作用域,以便可以通过func1和func2关闭它。 Is there a cleaner approach? 有没有更清洁的方法?
If there is a cleaner way to invoke func1 & funct2 I'd appreciate that as well. 如果有一种更干净的方法来调用func1和funct2,我也将不胜感激。
I would use Bluebird's .using 我会用Bluebird的.using
Example straight from their API documentation 直接来自其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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.