【问题标题】:How to run a statement only when the loop (with functions inside it) have completed?如何仅在循环(其中包含函数)完成时运行语句?
【发布时间】:2020-11-29 10:50:10
【问题描述】:

这是我的代码。

router.route("/login").post((req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  Account.find().then((account) => {
    account.forEach((eachAcc) => {
      if (eachAcc.email.toUpperCase() === email.toUpperCase()) {
        bcrypt.compare(password, eachAcc.password, function (err, result) {
          if (result == true) res.status(200).json("Login Successful");
          else if (err) res.status(400).json("Error: " + err);
        });
      }
    });
    res.status(400).json("Invalid email or password");
  });
});

但我总是收到无效的电子邮件/密码,我希望仅在循环完成且电子邮件/密码不匹配时打印它。

请帮忙。

【问题讨论】:

标签: javascript node.js


【解决方案1】:

试试这个

    router.route("/login").post((req, res) => {
      const { email, password } = req.body;
      Account.find().then((account) => {
      let acc = account.find(
         (eachAcc) => eachAcc.email.toUpperCase() === 
            email.toUpperCase()
         );
      if (acc) {
         bcrypt.compare(password, acc.password, function (err, result) 
          {
            if (err) res.status(400).json("Error: " + err);
            else if (result) res.status(200).json("Login Successful");
            else res.status(400).json("Invalid password");
          });
         } else res.status(400).json("Invalid email");
       });
    });

【讨论】:

    【解决方案2】:

    您可以为此 setTimeout(()=>{//code here},300) 使用 setTimeout 函数。

    【讨论】:

    • 在这些情况下切勿使用 setTimeout。
    • 如果他必须等待一段时间才能获取数据,那将是非常糟糕的用户体验
    【解决方案3】:

    希望对你有帮助:

    router.route("/login").post((req, res) => {
      const { email, password } = req.body;
    
      Account.find().then((accounts) => {
        let match = false;
        for (acct of accounts) {
          if (acct.email.toUpperCase() !== email.toUpperCase()) continue;
    
          bcrypt.compare(password, acct.password, (err, result) => {
            if (err) {
              res.status(400).json("Error: " + err);
              break;
            }
            res.status(200).json("Login Successful");
            match = true;
            break;
          });
    
        }
        if (!match) res.status(400).json("Invalid email or password");
      });
    });

    【讨论】:

    • 我会试试这个。谢谢
    • 它不起作用,我总是得到 Invalid email/password
    • @sandy 你确定你的用户名和密码正确并且与bcrypt.compare()函数匹配吗?
    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2012-12-04
    相关资源
    最近更新 更多