快递不等承诺

时间:2020-08-19 23:02:20

标签: node.js express mongoose

router.post('/login', async (req, res) => {

  await Auth.findOne({ userEmail }, { userLoginInfo: 0 }).then((auth) => {
    console.log('1');
    console.log(res.header); <---------- header sent after console.log('1')
    // Check if user exists
    if (auth === null) {
      return res
        .status(400)
        .json({ authFailedMessage: 'Email or password is incorrect' });
    } else if (auth !== null) {
      console.log('auuuuuuth')
      console.log(res.header)
      console.log('auuuuuuth13412312')
      bcrypt.compare(password, auth.password).then((isMatch) => {
        if(isMatch) {
          console.log(res.header)
          console.log('matched!')
          console.log(res.header)
        } else if (!isMatch) {
          console.log(res.header)
          console.log('hhhhh?!')
          console.log(res.header)
        }
      })

我正在尝试验证用户,然后在cookie中发送jwt。但是,即使在对结果做任何事情之前,res标头也会触发。我尝试使用新的Promise(),但是在这种情况下,Promise返回值后它不会继续前进。对返回的猫鼬查询结果执行某些操作后,如何发送标头?

------新代码

router.post('/login', async (req, res) => {
  const logInEnvironment = browser(req.headers['user-agent']);
  const ipAddress = requestIp.getClientIp(req);
  const userEmail = req.body.userEmail.toLowerCase();
  const password = req.body.password;
  console.log('aa')
  console.log(res.header);
  // Form validation
  const validation = await validateLoginInput(req.body);
  console.log(res.header);
  console.log('ab')
  // Check validation
  if (!validation.isValid) {
    return res.status(400).json(validation.errors);
  }
  console.log(res.header);
  console.log('ac')
  // Find user by email

  const auth = await Auth.findOne({ userEmail }, { userLoginInfo: 0 })
    console.log(`auuuuth? ${auth}`);
    console.log(res.header);
    console.log('ad')

    if(auth !== null) {
      console.log('ahiuhiuhaisudf!')
    } else {
      console.log('whaitoh!?')
    }
 
});

------ console.log

aa
[Function: header]
a <------ from 'const validation = await validateLoginInput(req.body)'
[Function: header]
ab
[Function: header]
ac
auuuuth? {
  termsandconditions: {
    agreed: true,
  },

}
[Function: header]
ad
ahiuhiuhaisudf!

1 个答案:

答案 0 :(得分:1)

您的代码中有一个关于您如何“等待”诺言的问题。在使用.then()关键字时,您似乎在承诺上附加了await,它们都具有相同的作用。

await Auth.findOne({ userEmail }, { userLoginInfo: 0 }).then((auth) => {

您应该尝试删除.then()块并将已解决的诺言存储在变量中:

const auth = await Auth.findOne({ userEmail }, { userLoginInfo: 0 });
//Do what you want with the 'auth' here

让我知道这是否有帮助。