Release MySQL connections in a Promise.All

Viewed 671

I want to release connections given by a MySQL pool. In a "for" loop, the connections are correctly released, but if I use a Promise.All to do it asynchronized, I have some connections that are not closed. The problem is that, after a moment, I get the error "Too many connections", and I don't want to increase the max_connection number.

Do you know if, for any reason, MySQL connections can't be released in an asynchronous function ?

Here is how I create my pool :

dbPool = mysql2.createPool(Object.assign({}, defaultDBConfig, {
            database: 'my_db,
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0,
            multipleStatements: true,
            dateStrings: true
        }));

Here is the functions that I use :

/**
 * @description Allow to do a generic async forEach loop
 * @param {*} array
 * @param {*} callback
 */
async function asyncForEachPromised(array, callback) {
    await Promise.all(array.map(async (items) => {
        await callback(items);
    }));
/**
 * @description ExecuteQuery a query and return an object which contain the result or an error
 * @param {*} dbPool Connection pool
 * @param {*} query Query to executeQuery
 * @param {*} errorMessage Error message to send to the front-end
 * @param {*} elements Array of parameter to send in the query
 */
async function executeQuery(dbPool, query, errorMessage, elements) {

    const status = {
        error: null,
        result: null
    };

    const { error, connection } = await dbPool.getConnection();

    if (error) {
        console.log(error);
        status.error = 'Error when trying to connect to the database.';
    } else {
        try {
            const [rows] = await connection.promise().execute(query, elements);
            connection.release();
            status.result = rows;
        } catch (err) {
            console.log(err);
            status.error = errorMessage;
        }
    }
    return status;
}

Finally, there is a example of code that I use, on this case connections are not released :

const elements = [{prop1: 'a'},{prop1: 'b'}];
await asyncForEachPromised(elements, async (element) => {
    await executeQuery(dbPool, 'my query', 'my error message', [element.prop1]);
});

But on this case, they are correctly released :

const elements = [{prop1: 'a'},{prop1: 'b'}];
for (const [,element] of elements.entries()) {
    await executeQuery(dbPool, 'my query', 'my error message', [element.prop1]);
}
1 Answers

You can't do it like that.

Try this

Promise.all( arr )
.then( results => //your code with results)
.finally( () => //close connection)
.catch( e => //do what you need )

But... you should really try to use a connection pool. What do you use ? mysql node? https://github.com/mysqljs/mysql#pooling-connections

Related