coopernurse / node-pool

Generic resource pooling for node.js
2.38k stars 259 forks source link

Feature request: .use method? #167

Closed olalonde closed 6 years ago

olalonde commented 7 years ago

Would be nice to have a method that automatically acquires and releases a resource, e.g.:

pool.use(resource => {
  return resource.doSomething().then(console.log)
})

It would be implemented something like this (haven't tested):

  pool.use = (fn) => {
    pool.acquire().then(resource => {
      fn(resource)
        .then((result) => {
          pool.release(resource)
          return result
        }, (err) => {
          pool.release(resource)
          throw err
        })
    })
  }

Thoughts?

sandfox commented 7 years ago

At a first glance from my phone this seems a little bit like the promisey version of https://github.com/sandfox/generic-pool-decorator ?

olalonde commented 7 years ago

Yep, looks like :) Though I really this should be part of node-pool since it's such a common usage pattern.

olalonde commented 7 years ago
  pool.use = (fn) => {
    let resource
    return pool.acquire()
      .then(r => {
        resource = r
        return resource
      })
      .then(fn)
      .then((result) => {
        pool.release(resource)
        return result
      }, (err) => {
        pool.release(resource)
        throw err
      })
  }
sandfox commented 7 years ago

I think in general I'm down with this, I probably won't get much time to do anything about this till the weekend though.

malthe commented 5 years ago

Isn't the general case here that fn would return a promise itself?

binki commented 5 years ago

@malthe Yeah. The point is that it would return a Promise which would complete (reject or resolve) whenever it's done using the resource. Then it doesn't need to remember to release the resource because everything is scope-driven—especially when used with async/await.

binki commented 5 years ago

@malthe Are you confused about something? The example code here works both when fn returns a Promise and also when fn returns something other than a Promise. See docs for how .then() works.

malthe commented 5 years ago

The type definition has it like this: use<U>(cb: (resource: T) => U): PromiseLike<U>.

But I would have expected: use<U>(cb: (resource: T) => PromiseLike<U>): PromiseLike<U>.

binki commented 5 years ago

@malthe Looks like the type definitions are coming from the DefinitelyTyped project, not this project. The correct place to report issues about your typings is here. Please see also DefinitelyTyped’s contribution guide.