hba February 2016

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

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);
} 

Answers


mikefrey February 2016

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);
}

Post Status

Asked in February 2016
Viewed 2,891 times
Voted 4
Answered 1 times

Search




Leave an answer