Javascript 使用async await时,如何指定回调?

Javascript 使用async await时,如何指定回调?,javascript,node.js,asynchronous,node-postgres,Javascript,Node.js,Asynchronous,Node Postgres,我正在研究如何在以下方面使用事务: 但在下面的代码示例中: const { Pool } = require('pg') const pool = new Pool() (async () => { // note: we don't try/catch this because if connecting throws an exception // we don't need to dispose of the client (it will be undefined)

我正在研究如何在以下方面使用事务:

但在下面的代码示例中:

const { Pool } = require('pg')
const pool = new Pool()

(async () => {
  // note: we don't try/catch this because if connecting throws an exception
  // we don't need to dispose of the client (it will be undefined)
  const client = await pool.connect()

  try {
    await client.query('BEGIN')
    const { rows } = await client.query('INSERT INTO users(name) VALUES($1) RETURNING id', ['brianc'])

    const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
    const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
    await client.query(insertPhotoText, insertPhotoValues)
    await client.query('COMMIT')
  } catch (e) {
    await client.query('ROLLBACK')
    throw e
  } finally {
    client.release()
  }
})().catch(e => console.error(e.stack))
似乎该函数将立即执行。此外,似乎没有一种方法可以指定回调。将整个块从“(async()..”放入函数中,然后在try块末尾之前的final语句中添加:

await callbackfunction();

这有意义吗?添加回调函数的更好方法是什么?

等待的要点是不使用回调。它返回解析承诺的结果

无需等待:

do_something_asyc.then(function (data) { alert(data); });
等待:

var data = await do_something_asyc();
alert(data);

如果您使用的是承诺(这也是
async/await
在幕后使用的),您不需要回调。您不能在
之前添加
。然后(回调)
。catch(…
?@DavidDomain
然后
调用语义不同于“回调”调用语义吗(其中第一个参数表示可能的错误)。但是您可以执行
。然后(v=>callback(null,v)).catch(callback)
@robertklep Thx获取提示。很高兴知道。