我正在用 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/