javascript - 如何避免 NodeJs、Express 中的 If else hell

标签 javascript node.js express

我正在用 Nodejs 做一个项目,并表示我有一个逻辑来响应 ajax 调用,该调用通过其聚合框架查询 MongoDb 数据库,然后处理如此获得的结果。

MongoDB查询得到的结果

  [ { _id: 'ALR', count: 7 },
  { _id: 'WTK', count: 3 },
  { _id: 'BWL', count: 9 },
  { _id: 'BAT', count: 9 } ]

这个查询的回调函数

, function (err, counts) {
              if(err){
                console.log(err);
                return res.json({status:false, msg : err});
              }
              if(counts){
                console.log(counts);
                for (var i = 0; i < counts.length; i++) {
                    var type = counts[i]._id;
                    var count = counts[i].count;
                    if(type == "ALR"){
                      if(count < 5){
                        return res.json({status:false, msg : "Minimum 5 All-Rounders"});
                      } 
                    } else if(type == "BAT"){
                      if(count < 6){
                        return res.json({status:false, msg : "Minimum 6 Batsman"});
                      } 
                    } else if (type == "BWL"){
                      if(count < 6){
                        return res.json({status:false, msg : "Minimum 6 Bowlers"});
                      } 
                    } else if(type == "WTK"){
                      if(count < 3){
                        return res.json({status:false, msg : "Minimum 3 Wicket Keepers"});
                      } 
                    }
                } 
                return res.json({status:true, msg : "Squad Lauched"});
              }
          });

看起来我陷入了一种 If Else hell ,这段代码按预期工作,但如果有人至少可以提示以更好的方式执行此回调函数,我对此并不满意。

最佳答案

你的代码显然是非常重复的。一种更改方法是创建一个具有必要数据的对象,并基于该对象执行程序逻辑。例如:

var types = {
  ALR: { min: 5, name: 'All-Rounders' },
  BAT: { min: 5, name: 'Batsman' },
  BWL: { min: 4, name: 'Bowlers' },
  WTK: { min: 3, name: 'Wicket Keepers' },
};

for (var i = 0; i < counts.length; i++) {
  var type = counts[i]._id;
  var count = counts[i].count;
  if (types[type] && count < types[type].min) {
    return res.json({ status: false, msg: 'Minimum ' + types[type].min + ' ' + types[type].name });
  }
}

关于javascript - 如何避免 NodeJs、Express 中的 If else hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004764/

相关文章:

javascript - qTip2 渲染位置错误

javascript - 检查 Angular 中的 "mode"可见打印还是隐藏打印

javascript - 使用 JavaScript 在 html 输入上方添加 span

javascript - 用于提取网页内容的 Node.Js 模块?

javascript - 动态嵌套模型字段上的 Rails JavaScript 验证

node.js - 使用 Express 将额外数据包含到 Passport 中间件中

node.js - express.js 消息中的新行

javascript - 使用 Vue CLI 在 Node js 上进行 Express session

javascript - 当我将 'console.log(err.message)' 放入 express 应用程序的错误处理程序中时,它会无休止地记录,但为什么呢?

javascript - Node MySQL查询语法错误