如何在 nodeJS Q 承诺链和 return 承诺中释放资源?

How can I release a resource in a nodeJS Q promise-chain and return a promise?

承诺和问题的新手。

我想调用一个抽象底层资源的方法。该方法将打开资源进行一些处理然后关闭资源。

像这样:

module.exports = function fetchRecords() {
    return openConnection()
        .then(fetchRecords)
        .then(groupById)
        .catch(rethrow)
        .done(closeConnection);
} 

function closeConnection(result) {
   releaseConnection();
   return result;
}

因为我叫完成 return 不是一个承诺而是一个未定义的。

我希望在我的客户中我可以做到:

resource.fetchRecords().then(/*do something else*/);

看来我必须向客户端公开底层资源,这样我才能做:

resource
  .openConnection()
  .then(resource.fetchRecords)
  .then(/*do something else*/)
  .catch(/*..*/)
  .end(resource.close)

我不知道 Q 或 promises...但我想也许有更好的方法?

我应该这样做吗:

 module.exports = function fetchRecords() {
    return openConnection()
        .then(fetchRecords)
        .then(groupById)
        .then(closeConnection)
        .catch(rethrow);
} 

而不是 done 使用 finally,其中 returns 一个承诺:

https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback

module.exports = function fetchRecords() {
    return openConnection()
        .then(fetchRecords)
        .then(groupById)
        .catch(rethrow)
        .finally(closeConnection);
}