[英]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.