【问题标题】:How to return else of an if statement outside the for loop the if statement is in如何在if语句所在的for循环之外返回if语句的else
【发布时间】:2019-10-09 15:20:25
【问题描述】:

我有一个 sequelize 查询,可以找到所有具有 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`};
)};

【问题讨论】:

  • 你不能只保存一个状态指示它是否被找到并在循环后使用它吗?如果您要检查一封电子邮件,您就不能同时搜索该电子邮件吗?
  • 在邮件上提出请求然后检查权限似乎更容易

标签: javascript node.js


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多