【发布时间】: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