Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Exit script after async function

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();
like image 498
Oguntoye Avatar asked Sep 22 '18 21:09

Oguntoye


2 Answers

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.

like image 117
Estus Flask Avatar answered Oct 24 '22 14:10

Estus Flask


This solution avoids adding process.exit on each block of the try-catch

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

  await createTable(Schemas.userModel, 'Users');
  await createTable(Schemas.orderModel, 'Orders');
};

dbInit().finally(() => {
  process.exit();
});
like image 25
kato2 Avatar answered Oct 24 '22 14:10

kato2