如何在for循环之外的if循环中返回if语句的else

时间:2019-10-09 15:20:25

标签: javascript node.js

我有一个序列查询,该查询查找所有具有can_upload = 1属性的用户,该用户可以将文件上传到数据库。为此,我遍历了所有具有can_upload = 1属性的用户,然后有一个if语句,该语句检查在请求标头中发送的用户电子邮件是否与在for循环中迭代的任何单个电子邮件匹配。

这部分很好,但是我无法在此for循环中返回else {},因为如果req标头中的电子邮件不等于所迭代的第一个值,则循环将停止并且else {}语句将返回无需检查循环中的其他值。

users.findAll({where: {can_upload: 1}}).then(projectUsers=>{ 
var email = "";
 for (let i=0; i<projectUsers.length;i++){
   email=projectUsers[i].dataValues.email_address;
    if (email === req.headers.email_address) {
         //do a bunch of stuff
         res.status(200).send{`message: success`};
    }
 }
//somehow return the else here which would return 
res.status(401).send{`message: user is not authorized to upload`};
)};

2 个答案:

答案 0 :(得分:3)

您可以这样做:

users.findAll({where: {
    can_upload: 1, 'dataValues.email_address': req.headers.email_address}
}).then(projectUsers=>{ // do whatever you need here // }

答案 1 :(得分:1)

为什么不只在查询中包含电子邮件到数据库,而不能返回所有can_upload = 1的用户,

users.findAll({where: {
    can_upload: 1, email_address: req.headers.email_address} }).then(projectUsers=>{ /* logic */ })

现在只需检查projectUsers的长度是否大于0