首页 > 解决方案 > 如何在if语句所在的for循环之外返回if语句的else

问题描述

我有一个 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`};
)};

标签: javascriptnode.js

解决方案


你可以这样做:

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

推荐阅读