简体   繁体   中英

Manage nested queries for mysql in Node.js

I'm trying to create a function for writing to a MySql database instance through a Node.js application using the mysql npm package.
I created something that works but I'm not satisfied because this code seems too much complicated with 4 nested if s.
I retrieve a connection from the connection pool and I can have an error. Then, only if I don't have an error, I can try to start a transaction, and potentially another error can be generated. At this point, only if the transaction starts correctly I can run a query but also here another error can potentially occur. Finally, the transaction is ready to be committed but also here another error can be generated.

I'm used to Java try / catch / finally and not an expert of JavaScript but I really like this language and would like to understand better how to manage functions, callbacks and promises.
I don't understand if it's the library that doesn't allow to make cleaner code or what.

Can someone help me in improving the readability and maintainability of this code?


import mysql from "mysql";

// Creating the connection pool 
const pool = mysql.createPool({
    host: "SOME_HOST",
    user: "SOME_USER",
    port: "SOME_PORT",
    password: "SOME_PASSWORD",
    database: "SOME_DB_NAME"
});


function runQueries() {
    pool.getConnection(function (err, connection) {
        if (err) throw err; // not connected!
        connection.beginTransaction(function (err) {
            if (err) { throw err; }
            connection.query("some query", function (error, results) {
                if (error) {
                    return connection.rollback(function () {
                        throw error;
                    });
                }
                connection.commit(function (error) {
                    if (error) {
                        return connection.rollback(function () {
                            throw error;
                        });
                    }
                });
                console.log(results);
            });
        });
        if (connection) connection.release();
    });
}

Thanks in advance.

Try using async/await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

const runQueries = async () => {
    const connection = await pool.getConnection()
    await connection.beginTransaction()
    const { error, results } = await connection.query("some query")
    if (error) return connection.rollback( 
    console.log(results)
    if (connection) await connection.release();          
}

At the end I used Node MySQL 2 with a "promise pool" : is much more readable, linear, and allows to use try/catch/finally blocks consistently.

import mysql from "mysql2";

const pool = mysql.createPool({
    host: "SOME_HOST",
    user: "SOME_USER",
    port: "SOME_PORT",
    password: "SOME_PASSWORD",
    database: "SOME_DB_NAME"
});
const promisePool = pool.promise();

async function runQueries() {
    let connection;
    try {
        connection = await promisePool.getConnection();
        await connection.beginTransaction();
        const results = await connection.query("some query");
        await connection.commit();
        console.log(results); // or console.table(results);
    }
    catch (error) {
        console.log(error);
    }
    finally {
        if (connection) connection.release();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM