0

我有以下代码:

  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});}
     });
4

2 回答 2

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 );
    }
 }

您甚至可以通过这种方式抽象简单的插入/更新样式查询。

于 2012-04-09T00:06:59.373 回答
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)}
});
于 2012-04-09T00:26:45.760 回答