2

New to promises & Q.

I would like to call a method which abstracts an underlying resource. The method would open the resource do some processing then close the resource.

Something like this:

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

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

Since I'm calling done the return is not a promise but an undefined.

I was hoping that in my client I could do:

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

It looks like I have to expose the underlying resource to the client so that I can do:

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

I don't know Q or promises...but I thought maybe there is a better way?

Should I just do:

 module.exports = function fetchRecords() {
    return openConnection()
        .then(fetchRecords)
        .then(groupById)
        .then(closeConnection)
        .catch(rethrow);
} 
hba
  • 7,406
  • 10
  • 63
  • 105
  • You should use the [promise disposer pattern](https://stackoverflow.com/questions/28915677/what-is-the-promise-disposer-pattern) – Bergi Feb 08 '16 at 22:09
  • @Bergi I'll give that a shot as well... – hba Feb 08 '16 at 22:11

1 Answers1

2

Instead of done use finally, which returns a promise:

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

module.exports = function fetchRecords() {
    return openConnection()
        .then(fetchRecords)
        .then(groupById)
        .catch(rethrow)
        .finally(closeConnection);
}
mikefrey
  • 4,653
  • 3
  • 29
  • 40