【问题标题】:How can I release a resource in a nodeJS Q promise-chain and return a promise?如何在 nodeJS Q 承诺链中释放资源并返回承诺?
【发布时间】:2016-05-18 16:35:48
【问题描述】:

Promise 和 Q 的新手。

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

类似这样的:

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

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

由于我调用的是 done,所以 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);
} 

【问题讨论】:

标签: node.js promise q


【解决方案1】:

而不是done 使用finally,它返回一个承诺:

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

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

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多