2015-05-18 158 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不正確,因爲您尚未使用連接。