两个ifs中的find调用都有以函数(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);
});
}
发布于 2016-05-15 19:56:21
最明显的干燥代码的方法是将回调提取到一个命名函数,该函数可以作为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);
https://stackoverflow.com/questions/37237907
复制相似问题