最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The correct way to invoke an async function main? - Stack Overflow

programmeradmin2浏览0评论

I have some nodejs scripts - i.e. processes which do a job and plete, 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?

I have some nodejs scripts - i.e. processes which do a job and plete, 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?

Share Improve this question edited Apr 5, 2019 at 9:10 fadedbee asked Apr 5, 2019 at 8:35 fadedbeefadedbee 44.9k48 gold badges200 silver badges352 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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.

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

You can also define async functions using an async function expression.

async function f() {

  try {
    let response = await fetch('http://no-such-url');
  } catch(err) {
    alert(err); // TypeError: failed to fetch
  }
}

f();

you can also immediately call an asynce function using the syntax below

(async () => {

})();
发布评论

评论列表(0)

  1. 暂无评论