我怎样才能释放一个资源在一个node QS promise链中并返回一个promise?
新承诺&Q.
我想调用一个抽象底层资源的方法。 该方法将打开资源做一些处理,然后closures资源。
像这样的东西:
module.exports = function fetchRecords() { return openConnection() .then(fetchRecords) .then(groupById) .catch(rethrow) .done(closeConnection); } function closeConnection(result) { releaseConnection(); return result; }
由于我打电话完成,回报不是一个承诺,而是一个未定义的。
我希望在我的客户中我可以做到:
resource.fetchRecords().then(/*do something else*/);
看起来我必须将底层资源公开给客户端,以便我可以这样做:
resource .openConnection() .then(resource.fetchRecords) .then(/*do something else*/) .catch(/*..*/) .end(resource.close)
我不知道Q或诺言…但我想也许有更好的办法?
我应该这样做:
module.exports = function fetchRecords() { return openConnection() .then(fetchRecords) .then(groupById) .then(closeConnection) .catch(rethrow); }
而不是finally
使用,它返回一个承诺:
https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback
module.exports = function fetchRecords() { return openConnection() .then(fetchRecords) .then(groupById) .catch(rethrow) .finally(closeConnection); }