Promise still pending even after knex.destroy()

Viewed 502

I'm having some progress learning about Promises, but I don't understand why the knex behave like this in node.

I successfully receive a query and console.log it out, but when I run

node filename.js

The process doesn't quit and stay there after successfully print, like if the Promise still pending. Should not the knex.destroy() in the .finally statement end the Promise?

async function SELECT_ALL_P() {
  const transaction = await knex.transaction()
  return knex
  .select('*')
  .from('p')
  .then(items => {
    return console.log(items)
  })
  .catch(error => {
    console.log(error)
  })
  .finally(function() {
    knex.destroy()
  })
}

SELECT_ALL_P()

I event tried like

.then(items => {
    knex.destroy()
    return console.log(items)
  })

But it didn't worked also. I need to Ctrl+C in terminal to quit the node execution.

1 Answers

When knex.destroy() is called, knex will not allow new queries/transactions to be started and then waits that all of those are finished before shutting down everything and destroying pool.

In your example you are never doing transaction.commit() nor transaction.rollback(err), so that connection is never returned to the pool and calling knex.destroy() never completes (maybe it does after some timeout).

Actually you are never even making any queries through that transaction. If you like to just create an option to have transaction when needed you can create transactionProvider, which then lazily creates a singleton transaction, when it is requested for the first time.

Related