重构DRY代码的Node.JS回调

时间:2016-05-15 11:49:27

标签: javascript node.js refactoring dry

ifs中的查找调用都有以函数(e,docs)开头的回调。 什么是一个干净的方式来重构它是DRYer? 感谢。

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

1 个答案:

答案 0 :(得分: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);