繁体   English   中英

难以处理JavaScript中的Promises

[英]Difficulty handling Promises in javascript

嗨,有人可以看看我的代码吗? 我将在后端构建身份验证,这是一个辅助项目,目的是提高我对JavaScript的理解。

我不确定为什么猫鼬发现的承诺会返回未定义的内容。

我有两个需要帮助的功能。 一种是帮助功能,该功能将传递给控制器​​。

 import db from '../models';
 import bcrypt from 'bcrypt';
 import validateLogin from '../validations/login';
 import isEmpty from 'lodash/isEmpty';
 const loginController = {};

 loginController.login = function(req,res){
     validateLogin(req.body).then(({isValid, errors }) => {
     // isValid is undefined here
     // This is the problem
        if(isValid){
             // give token
           res.status(200).json({
              success: true,
             token: 'here is your token'
          });
       } else {
          res.status(401).json({
             errors
          });     
       }    
   }).catch(err =>{
        console.log(err)
   });      
};

export default loginController;

另一个是控制器函数本身,它将根据辅助函数是否返回有效响应来使用令牌。

  import validator from 'validator';
  import db from '../models';
  import isEmpty from 'lodash/isEmpty';
  import bcrypt from 'bcrypt';

  function validateLogin(data){
      const {  userInput, password } = data;
      const errors = {};
      if(validator.isEmpty(userInput)){
         errors.userInput = 'username is required';
      }   
      if(validator.isEmpty(password)){
         errors.password = 'password is required';
      }   
      return db.User.find({$or:[{ username: userInput }, { email: userInput }]}).then(existingUser =>{
         if(existingUser.length > 0){
            // User exists, check if password matches hash
            const user = existingUser[0];
            bcrypt.compare(password, user.password_digest).then(valid => {
               if(!valid){
                  errors.password = 'Invalid Password';
               }
               console.log('from prmomise');
               return {
                  isValid: isEmpty(errors),
                  errors
                };
             }).catch(err => console.log(err));
          } else {
             errors.userInput = 'username or email does not exist';
             return {
                isValid: isEmpty(errors),
                errors
             };
          }
      });
   }

   export default validateLogin

看起来bcrypt调用缺少return值:

return bcrypt.compare(password, user.password_digest).then(valid => {
    // password check and returning result object
}).catch(err => console.log(err));

没有它,您的validateLogin函数最终将返回一个承诺,该承诺将解析为undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM