简体   繁体   English

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

[英]How to return else of an if statement outside the for loop the if statement is in

I have a sequelize query that finds all users who have an attribute of can_upload = 1 which allows them to upload file to database.我有一个 sequelize 查询,可以找到所有具有 can_upload = 1 属性的用户,该属性允许他们将文件上传到数据库。 For that I loop through all the users who have attribute of can_upload = 1 and then I have an if statement which checks if the email of the user sent in request header matches any single on that was iterated in the for loop.为此,我遍历所有具有 can_upload = 1 属性的用户,然后我有一个 if 语句,该语句检查在请求 header 中发送的用户的 email 是否与在 for 循环中迭代的任何单个匹配。

This part is fine, but I cannot return the else{} within this for loop since, if the email in the req header is not equal to the first value iterated then the loop will stop and the else{} statement will return without checking the other values in the loop.这部分很好,但我不能在这个 for 循环中返回 else{},因为如果 req header 中的 email 不等于迭代的第一个值,那么循环将停止并且 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`};
)};

You can do this:你可以这样做:

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

Why not just include the email in the query to the database instead of returning ALL the users with can_upload = 1,为什么不在对数据库的查询中包含 email 而不是返回所有 can_upload = 1 的用户,

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

And now just check if projectUsers has a length > 0现在只需检查 projectUsers 的长度是否 > 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM