【问题标题】:When using async await, how do you specify a callback?使用异步等待时,如何指定回调?
【发布时间】:2017-10-13 16:08:31
【问题描述】:

我正在研究如何在以下方面使用交易:

https://node-postgres.com/features/transactions

但是在下面的代码示例中:

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块结束之前的最后一条语句中,添加:

await callbackfunction();

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

【问题讨论】:

  • 如果你使用 Promise,你不应该需要回调(这也是 async/await 在幕后使用的)。
  • 你不能在.catch(... 之前添加.then(callback) 吗?
  • @DavidDomain then 调用语义不同于“回调”调用语义(其中第一个参数表示可能的错误)。但你可以做.then(v => callback(null, v)).catch(callback)
  • @robertklep 谢谢提示。很高兴知道。

标签: javascript node.js asynchronous node-postgres


【解决方案1】:

等待的重点是您不使用回调。它返回解决承诺的结果。

无需等待:

do_something_asyc.then(function (data) { alert(data); });

等待:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2018-04-06
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多