2012-04-08 64 views
0

我有以下代碼:socket.io回調

client.keys("key_"+id, function (err, replies){ 
     if (replies.length > 0){ 
     client.sunion(replies,function (err, replies){ 
      {...} 
     }); 
     }else{...} 
    }); 

下面我有這個功能

pg.connect(conString, function(err, client) {some code}); 

但我想在第一段代碼執行pg.connect而不是...。 如何儘量避免複製代碼和內存泄漏,pg.connect函數將在所有{...}中相同。

有了複製的代碼,這將是這樣的:

client.keys("key_"+id, function (err, replies){ 
     if (replies.length > 0){ 
     client.sunion(replies,function (err, replies){ 
      pg.connect(conString, function(err, client) {some code}); 
     }); 
     }else{pg.connect(conString, function(err, client) {some code});} 
    }); 

回答

1

記住你是在使用JavaScript和可以定義小助手功能,以減少你的打字...

function withConnect(callback) { 
    return pg.connect(conString, callback); 
} 

例如將節省你一些時間......但是如果錯誤處理程序總是一樣的呢?

function withConnect(callback) { 
    return pg.connect(conString, function(err, client) { 
     if (err) { 
      handleError(err); 
     } 
     // we might still want something special on errors... 
     callback.apply(this, arguments); 
    } 
} 

你甚至可以用這種方式抽象簡單的插入/更新樣式查詢。

0

你可以嘗試(如果 「一些代碼」 部分是相同的):

function connectFunc() { 
    return function (err){ 
     pg.connect(conString, function(err, client) {some code}); 
    }; 
} 

client.keys("key_"+id, function (err, replies){ 
    if (replies.length > 0){ 
     client.sunion(replies, connectFunc()); 
    } else { connectFunc()(err)} 
}); 

或者,如果 「一些代碼」 而異:

function connectFunc(some_code) { 
    return function (err){ 
     pg.connect(conString, function(err, client) {some_code();}); 
    }; 
} 

client.keys("key_"+id, function (err, replies){ 
    if (replies.length > 0){ 
     client.sunion(replies, connectFunc(function(){some code})); 
    } else { connectFunc(function(){some other code})(err)} 
});