Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-postgres transactions with callbacks or async/await?

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:

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.

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

like image 474
Rob Johansen Avatar asked Apr 11 '17 16:04

Rob Johansen


1 Answers

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.

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

like image 195
Rob Johansen Avatar answered Nov 15 '22 23:11

Rob Johansen