coopernurse / node-pool

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

Suggested Feature: borrowTimeoutMillis #302

Open daveroberts opened 2 years ago

daveroberts commented 2 years ago

I implemented a feature in my usage of this library to throw an error if the client hasn't been returned after a set amount of time, and automatically return the client to the pool:

async function use_client(fn){
  let client = await pool.acquire()
  let promises = [fn(client)]
  if (opts.borrowTimeoutMillis){
    promises.push(new Promise((_, reject)=>setTimeout(()=>reject('BORROW_TIMEOUT_REACHED'), opts.borrowTimeoutMillis)))
  try {
    return await Promise.race(promises)
  } finally {.if (client){.pool.release(client) } }
}

use_client(client => {./*your code using the client here */ })

Edit: I modified the code to only throw the timeout if opts.borrowTimeoutMillis is set

Would be good to have this incorporated into the library somehow, I'm sure I'm not the first to implement something like this.

alanwu4321 commented 1 year ago

Will setTimeout cause overhead? - is there a way to not check this every time I use the client

daveroberts commented 1 year ago

I modified the function above to only throw the timeout, and only call setTimeout, if opts.borrowTimeoutMillis is set. More to the point though, the code snippet above was only representing how I was using the pool library in my code, and wasn't supposed to be generic to everyone's code. If incorporated into this library, I'd expect edits would need to be made to accommodate more use cases.