当使用asynchronous等待,如何指定一个callback?

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

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

看来这个函数会立即执行。 也似乎没有一种方法来指定callback。 将“(async()…)”的整个块放入一个函数中,然后在try块结束之前的最后一个语句中添加:

 await callbackfunction(); 

那有意义吗? 什么是更好的方式来添加callback函数?

等待的一点是你不使用callback。 它返回解决承诺的结果。

无需等待:

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

等待:

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