I have the following code:
client.keys("key_"+id, function (err, replies){
if (replies.length > 0){
client.sunion(replies,function (err, replies){
{...}
});
}else{...}
});
below I have this function
pg.connect(conString, function(err, client) {some code});
But I want execute pg.connect
instead of ...
in first piece of code.
How best to do to avoid copying code and memory leaks, pg.connect
function will be the same in all {...}
.
With copying code this will be look like:
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});}
});
Remember that you are working with JavaScript and can define little helper functions to reduce your typing...
function withConnect( callback ) {
return pg.connect( conString, callback );
}
for instance will save you some time... But what if the error handler is always the same?
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 );
}
}
You could even abstract simple insert/update style queries this way.
You can try (if the "some code" sections are the same):
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)}
});
Or, if the "some code" varies:
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)}
});