Javascript: Exit script after async function

11,738

Node.js exits when event loop runs dry. If the script doesn't exit after async function ends, this means that there is something that prevents it from being completed.

In this case there are database queries but database connection isn't closed, this is the cause. Also control flow is messed up, there's no resulting promise to chain.

It should be:

  const createTable = async (creationQuery, tableName) => {
    try {
      const created = await client.query(creationQuery);
      if (created) logger(`'${tableName}' table created successfully`);
    } catch (err) {
      logger(err.message);
    }
  };

const dbInit = async () => {
  try {
    await createTable(Schemas.userModel, 'Users');
    await createTable(Schemas.orderModel, 'Orders');
    process.exit(0);
    // or close database connection
  } catch (err) {
    process.exit(1);
  }
};
dbInit();

All rejections should be handled with either promise catch() or try..catch. Not handling them in this case can result in UnhandledPromiseRejectionWarning console output and the script that never exits.

Share:
11,738
Oguntoye
Author by

Oguntoye

Updated on June 13, 2022

Comments

  • Oguntoye
    Oguntoye almost 2 years

    I am trying to create a database setup script for a nodeJS project. I have the following async function createTable that queries a PostgreSQL database.

    The problem is that the script does not quit after all the operations have been carried out. I have tried appending process.exit(0) to the end of the file but that just prematurely kills the script (I think it executes while the async operations are running).

    How do I properly exit the script after operations are done?

    const dbInit = () => {
      const createTable = async (creationQuery, tableName) => {
        try {
          const created = await client.query(creationQuery);
          if (created) logger(`'${tableName}' table created successfully`);
        } catch (err) {
          logger(err.message);
        }
      };
    
      createTable(Schemas.userModel, 'Users');
      createTable(Schemas.orderModel, 'Orders');
    };
    dbInit();
    
  • imsheth
    imsheth over 3 years
    This saved me hours of search, thank you! @estus-flask