使用回调或async / await的node-postgres事务?

时间:2022-06-06 01:02:44

I'm running Node 7.6.0, which supports async/await. The node-postgres client pool supports async/await, and has a nice example here. However, the example for transactions in node-postgres (here) uses callbacks instead of async/await. Despite that example, I thought I'd try transactions with async/await in a quick test:

我正在运行Node 7.6.0,它支持async / await。 node-postgres客户端池支持async / await,这里有一个很好的例子。但是,node-postgres中的事务示例(此处)使用回调而不是async / await。尽管如此,我还是认为我会在快速测试中尝试使用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!';

This seems to work just fine, but I was told by a node-postgres contributor that this is a bad idea. Unfortunately, he didn't take the time to explain why this is a bad idea—he just said to seek an answer on Stack Overflow.

这似乎工作得很好,但我被一个节点postgres贡献者告知,这是一个坏主意。不幸的是,他没有花时间解释为什么这是一个坏主意 - 他只是想在Stack Overflow上寻求答案。

Why is it a bad idea to perform transactions with async/await instead of callbacks in node-postgres?

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

1 个解决方案

#1


4  

The creator of node-postgres (brianc) graciously provided an excellent response to my original question on GitHub. The short answer is that it is not a bad idea to perform transactions with async/await.

node-postgres(brianc)的创建者慷慨地对我在GitHub上的原始问题做出了很好的回应。简短的回答是,使用async / await执行事务并不是一个坏主意。

See his full response here: https://github.com/brianc/node-postgres/issues/1252#issuecomment-293899088

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

#1


4  

The creator of node-postgres (brianc) graciously provided an excellent response to my original question on GitHub. The short answer is that it is not a bad idea to perform transactions with async/await.

node-postgres(brianc)的创建者慷慨地对我在GitHub上的原始问题做出了很好的回应。简短的回答是,使用async / await执行事务并不是一个坏主意。

See his full response here: https://github.com/brianc/node-postgres/issues/1252#issuecomment-293899088

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