【问题标题】:Refactor Node.JS callbacks for DRY code为 DRY 代码重构 Node.JS 回调
【发布时间】:2016-05-15 11:49:27
【问题描述】:

ifs 中的两个 find 调用都有以函数开头的回调(例如,文档)。 将它重构为 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);
        });
    }

【问题讨论】:

    标签: javascript node.js refactoring dry


    【解决方案1】:

    DRY 代码最明显的方法是将回调提取到命名函数,该函数可以作为回调传递给 find 方法的最后一个参数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      相关资源
      最近更新 更多