Skip to content
Advertisement

How to run a statement only when the loop (with functions inside it) have completed?

This is my code.

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");
  });
});

But I am always getting Invalid email/ password, I want it to be printed only when loop has completed and email/ password didn’t match.

Please help.

Advertisement

Answer

Try this

    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");
       });
    });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement