2015-05-18 111 views
2

我想知道的连接应使用它后释放,我已经看到了这几个选项:释放连接,连接池Node.js加载

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)? 

}); 

或者,也许它应该被释放两种错误和非错误情况?

回答

4

正确的地方是#2或#5。

您想要在完成使用后释放连接。

#6会出错,因为query()是异步的,所以它会在连接完成之前和回调触发之前立即返回。所以,在你完成之前,你会发布连接。

#5是正确的,因为回调已经触发,并且您已经完成了您要做的所有事情。请注意,这假定您不使用return在该点之前退出该功能。 (有些人在if (err)块中这样做。)

如果您没有在回调中的任何地方使用连接,#2也是正确的。如果你在回调中使用它,那么你不想在你使用它之前释放它。

#3和#4不正确,除非您使用这两个他们。否则,您只能在某些情况下释放连接。

#1不正确,因为您尚未使用连接。