node-pool icon indicating copy to clipboard operation
node-pool copied to clipboard

Suggested Feature: borrowTimeoutMillis

Open daveroberts opened this issue 2 years ago • 2 comments

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.

daveroberts avatar Oct 06 '22 17:10 daveroberts

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

alanwu4321 avatar Oct 12 '22 09:10 alanwu4321

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.

daveroberts avatar Oct 12 '22 09:10 daveroberts