繁体   English   中英

关闭JavaScript中承诺的连接的最干净的方法是什么

[英]What is the cleanest way to close promised connection in javascript

使用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和func2关闭它。 有没有更清洁的方法?

如果有一种更干净的方法来调用func1和funct2,我也将不胜感激。

我会用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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM