Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Program doesn't end after async function is called

I am just starting with postgresql.

I have successfully made connection with cloud database and retrieved data using nodejs ‘postgres’ package, but the program doesn’t end after it logs all the data on console, it’s still running. Why is that?

import postgres from 'postgres'
import "dotenv/config"

const sql = postgres({
  host: process.env.DATABASE_HOST,
  database: process.env.DATABASE_NAME,
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  ssl: 'require',
})

async function getInfo() {
  const users = await sql`
  select * from information_schema.tables
  `

  return users
}

getInfo().then((data) => console.log(data))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The node project will still run because of the database connection, you need to end it after retrieving the data.

async function getInfo() {
  try {
    const users = await sql`
      select * from information_schema.tables
    `;
    return users;
  } finally {
    sql.end(); // Close the connection
  }
}

Also, optionally you could force the node to shutdown with process.exit(0)

getInfo().then((data) => {
  console.log(data);
  process.exit(0);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading