Search code examples
javascriptnode.jsasync-awaitnode-mysql2

The correct way to invoke an async function main?


I have some nodejs scripts - i.e. processes which do a job and complete, rather than run continuously.

I use async functions, for example:

const mysql = require('mysql2/promise');
...

async function main() {
    var conn = await mysql.createConnection(config.mysql);
    ...
    var [response, error] = await conn.execute(`
        DELETE something
        FROM some_table
        WHERE field = ?
    `, [value]);
    ...

Is the following code:

main().then(() => process.exit(0)).catch(err => { console.error(err); process.exit(1); });

the best/correct way to start execution of the async code?

(It works, but I want to make sure that I'm not leaving any holes which might cause surprises, such as exceptions being silently swallowed.)

Why does conn.execute() return an error (which I need to manually check) rather than throwing one?


Solution

  • The use of then together with async..await isn't necessary because it's syntactic sugar for then.

    Entry point could be async IIFE (IIAFE):

    (async () => {
      try {
        var conn = await mysql.createConnection(config.mysql);
        ...
        var [response] = await conn.execute(`
            SELECT something
            FROM some_table
            WHERE field = ?
        `, [value]);
        ...
        process.exit(0);
      } catch (err) {
        console.error(err);
        process.exit(1);
      }
    })();
    

    There also may be no need for process.exit(0) if the connection was closed.

    Why does conn.execute() return an error (which I need to manually check) rather than throwing one?

    It doesn't, and isn't conventional for promise-enabled functions to return an error in a result.

    Callback-based execute uses error-first callback for errors. Promise-based execute can't throw an error because it returns a promise which is rejected in case of error.

    As the documentation shows, the second element is fields and not error:

    const [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
    

    It may return rejected promise which can be caught with try..catch inside async function in case of error.