2016-05-15 76 views
0

在if中找到调用都有以函数开头的回调(e,docs)。 干净的方式将它重构为DRYer? 谢谢。DRY代码的重构Node.JS回调

if (connection_id == null) { 
     id_connectionsCollection.find({}, {}, function (e, docs) { 
      if (e) { 
       return callback(e); 
      } 
      var connectionDetails = null; 
      if (docs == null || docs.length == 0) {//if no connections found, use default from config 
       connectionDetails = defaultConnectionDetails 
      } 
      else { 

       connectionDetails = docs[0];//just get the first one 
      } 

      return callback(null, connectionDetails); 
     }); 

    } 
    else { 
     id_connectionsCollection.find({name: connection_id}, {sort: {updated_at: -1}}, function (e, docs) { 
      if (e) { 
       return callback(e); 
      } 
      var connectionDetails = null; 
      if (docs == null || docs.length == 0) { 
       connectionDetails = defaultConnectionDetails; 
      } 
      else { 

       connectionDetails = docs[0];//just get the first one 
      } 
      return callback(null, connectionDetails); 
     }); 
    } 

回答

0

擦干你的代码的最明显的方法是你的回调提取到可以为你的回调来传递你的find方法的最后ARG命名函数:

// Can probably think of a better name here... 
doCallback = function(e, docs) { 
     if (e) 
     return callback(e); 

     var connectionDetails = null; 

     if (docs == null || docs.length == 0) 
     connectionDetails = defaultConnectionDetails; 
     else 
     connectionDetails = docs[0];//just get the first one 

     return callback(null, connectionDetails); 
} 

if (connection_id == null) 
    id_connectionsCollection.find({}, {}, doCallback); 
else 
    id_connectionsCollection.find({name: connection_id}, {sort: {updated_at: -1}}, doCallback);