javascriptmysqlnode.js

Do I need to use await when calling connection.release() in mysql2?


I'm working with the mysql2 Node.js library and managing connections through a connection pool. In some of the examples I've seen, connection.release() is called with await, but based on the documentation, release() seems to be a synchronous method that doesn't return a promise.


let connection;
try {
    connection = await db.getConnection(); // Using await to get the connection
    await connection.beginTransaction();   // Using await to begin the transaction
    
    // Some other database operations go here
    
} catch(error){

}finally {
    if (connection) {
        await connection.release(); // Do I need to await here?
    }
}



Solution

  • As jsejcksn commented, the .release() method returns void (which is the same as undefined).

    The source of .release() indeed returns this._pool.releaseConnection(this), but the source of .releaseConnection() returns undefined (effective value of void) or throws some error.

    As Jaromanda X commented, the await of something that is not asynchronous doesn't break the code execution.

    So, the final logic conclusion is that you don't need to await a .release() call, yet you still can (maybe to prevent error if the method is changed to async or return a promise in the future).