Reputation: 21
I am using the finally block written in node.js to close the database connection i have opened in the code. The code snippet is attached below.
Problem i am facing :- When i execute the below code on local machine, my finally blocks gets executed and this gets consoled "Response after dbconnection close:".
But when i am executing it in AWS lambda, i get response from my last then block and when my finally block executes it does not console the "Response after dbconnection close:" in function logs.
So the connection remains open.
It gets closed when i hit the lambda function again. but leaves behind the Open connection from the latest execution.
Please let me know how to use finally block properly or shall i close the connection in last then block?
exports.executeSelectQueryPromise = (sql, args, parameters) => {
sql = " SELECT * FROM ( " + sql + " ) as dataTable ";
let DBConnection;
return mysql.createConnection(process.env)
.then(async (conn) => {
DBConnection = conn;
return DBConnection.query(sql, args);
}).then(async (rows) => {
let result = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": [],
"isBase64Encoded": false
}
return result;
}).catch(async (error) => {
console.log("Error: ", error);
let err = {
"statusCode": 400,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": [],
"isBase64Encoded": false
}
return err;
})
.finally(async () => {
console.log("DB connection type: ", typeof DBConnection);
if (DBConnection && DBConnection.end) {
DBConnection.end()
.then(res => console.log("Response after dbconnection close: ", res))
.catch(e => console.log("Error in dbconnection close: ", e));
}
});
}
Upvotes: 0
Views: 430
Reputation: 597
A much better practice is to close your connection soon after the query gets executed irrespective of being executed successful or unsuccessful.
Upvotes: 1