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

时间:2017-10-13 07:36:47

标签: javascript node.js asynchronous node-postgres

我正在研究如何使用交易:

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();

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

1 个答案:

答案 0 :(得分:2)

等待的一点是你不使用回调。它返回解析promise的结果。

没有等待:

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

等待:

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