带回调或异步/等待的节点 postgres 事务?

2024-05-12

我正在运行 Node 7.6.0,它支持 async/await。 node-postgres 客户端池支持 async/await,并且有一个很好的示例here https://github.com/brianc/node-pg-pool#plays-nice-with-asyncawait。但是,node-postgres 中的事务示例(here https://github.com/brianc/node-postgres/wiki/Transactions)使用回调而不是异步/等待。尽管有这个例子,我想我应该在快速测试中尝试使用 async/await 进行事务:

let client = null;

try {
    client = await this.pool.connect();
} catch (error) {
    console.log('A client pool error occurred:', error);
    return error;
}

try {
    await client.query('BEGIN');
    await client.query('UPDATE foo SET bar = 1');
    await client.query('UPDATE bar SET foo = 2');
    await client.query('COMMIT');
} catch (error) {
    try {
        await client.query('ROLLBACK');
    } catch (rollbackError) {
        console.log('A rollback error occurred:', rollbackError);
    }
    console.log('An error occurred:', error);
    return error;
} finally {
    client.release();
}

return 'Success!';

这似乎工作得很好,但是有人告诉我 https://github.com/brianc/node-postgres/issues/1252一位 Node-Postgres 贡献者认为这是一个坏主意。不幸的是,他没有花时间解释why这是一个坏主意——他只是说要在 Stack Overflow 上寻求答案。

为什么在 node-postgres 中使用 async/await 而不是回调来执行事务是一个坏主意?


Node-Postgres 的创建者(brianc https://github.com/brianc)慷慨地对我在 GitHub 上提出的原始问题提供了极好的答复。简短的回答是,它是not与其进行交易是个坏主意async/await.

在这里查看他的完整回复:https://github.com/brianc/node-postgres/issues/1252#issuecomment-293899088 https://github.com/brianc/node-postgres/issues/1252#issuecomment-293899088

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带回调或异步/等待的节点 postgres 事务? 的相关文章

随机推荐