2016-05-15 62 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);