Reputation: 649
I am wondering where the connection should be released after using it, i have seen couple of options for that:
pool.getConnection(function(err, conn){
//conn.release() // should be placed here (1)?
conn.query(query, function(err, result){
//conn.release() // should be placed here (2)?
if(!err){
//conn.release() // should be placed here (3)?
}
else{
//conn.release() // should be placed here (4)?
}
//conn.release() // should be placed here (5)?
});
//conn.release() // should be placed here (6)?
});
Or maybe should it be released both error and non error cases?
Upvotes: 2
Views: 800
Reputation: 70055
The correct place is either #2 or #5.
You want to release the connection when you are done using it.
#6 would be wrong because query()
is asynchronous, so it would return right away before the connection is done with the query and before the callback fires. So you'd be releasing the connection before you are done with it.
#5 is correct because the callback has fired and you have done everything you are going to do with it. Note that this assumes that you do not use return
to exit the function before that point. (Some people do that in their if (err)
blocks.)
#2 is also correct if you aren't using the connection anywhere inside the callback. If you are using it in the callback, then you don't want to release it before you are done using it.
#3 and #4 are incorrect unless you use both of them. Otherwise, you are only releasing the connection in some situtations.
And #1 is incorrect because you haven't used the connection yet.
Upvotes: 5