0

I have a script called scheduler() which runs some queries on a Postgres database and then finished. I am having a problem where the script hangs in the terminal and does not exit after.

Here is my code:

scheduler.js

const {pool} = require("./db");
const scheduler = async function() {
    try {
        await auctionCheck();
        return pool.end().then(() => {
            console.log('Pool\'s closed');
            return;
        })

    } catch (e) {
        console.error(e)
        return;
    }

}
return scheduler();

db.js

const {Pool} = require("pg");
const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
});

pool.on('error', (err, client) => {
    console.error('Unexpected error on idle client', err)
    process.exit(-1)
})

pool.connect();

module.exports = {pool};

When I didn't have the pool.end() call, my script didn't exit, but it does not exit with the end() call either. The "Pool's closed" log is never printed. node-pg documentation says that I should do this to close connections (I assume that the reason my script isn't finishing is due to an open db connection.) I want to basically run some functions periodically and then have the script finish, but currently it just stays live. What am I doing wrong?

1 Answers1

1

It seems that the reason was that in db.js I had pool.connect(). Thus, when I did pool.end(), it couldn't close the connection because it did not have all of the clients in the pool - one being already created in db.js but never released. When I removed pool.connect() in db.js the process exited as it should.

  • You may have used the `pool.connect()` method but it is important that the returned client is released by calling `client.release()`. I assume that once the client is released the `pool.end()` function would terminate as well. – Elias May 10 '22 at 07:30