英文:
Promise returning undefined in nodejs
问题
以下是翻译后的代码部分:
const express = require('express');
const bcrypt = require('bcrypt');
let salt;
const loginUser = async (req, res) => {
const { email, password } = req.body;
try {
let user = await userModel.findOne({ email });
salt = await bcrypt.genSalt(10);
if (!user) return res.status(400).json("用户名或密码无效");
let validStatus = false;
let isValidPassword = await bcrypt.compare(password, user.password, (err, result) => {
// console.log(err);
console.log(result);
if (result) validStatus = true;
});
console.log(validStatus);
if (!isValidPassword) return res.status(400).json("用户名或密码无效");
const token = createToken(user._id);
res.status(200).json({ _id: user.id, name: user.name, email, token });
} catch (err) {
console.log(err);
}
};
希望这对你有帮助。如果需要进一步的帮助,请随时提问。
英文:
Here I was created one loginUser model which simply check if user is exists or not code is working fine but I am facing error in isValidPassword
it will always false condition even if the email and password is true.
Whenever I try to console.log(isValidPassword)
then it will return undefined and same case happening with validStatus
const express=require('express');
const bcrypt=require('bcrypt');
let salt;
const loginUser=async (req,res)=>{
const {email,password}=req.body;
try{
let user=await userModel.findOne({email});
salt= await bcrypt.genSalt(10);
if(!user) return res.status(400).json("invalid Username or passowrd");
let validStatus=false;
let isValidPassword = await bcrypt.compare(password,user.password,(err,result)=>{
// console.log(err);
console.log(result);
if(result) validStatus=true;
});
console.log(validStatus);
if(!isValidPassword) return res.status(400).json("invalid Username or passowrd");
const token=createToken(user._id);
res.status(200).json({_id:user.id,name:user.name,email,token});
}
catch(err)
{
console.log(err);
}
};
答案1
得分: 2
bcrypt.compare已经返回一个Promise,所以不需要传递回调函数给它。
英文:
bcrypt.compare already returns a promise so dont pass calback to it
答案2
得分: 2
你试图同时使用compare
中的回调函数和Promise。只需从compare
调用中移除回调函数(参见BCrypt with promises):
let isValidPassword = await bcrypt.compare(password,user.password)
英文:
You're trying to use both a callback and a Promise from compare
. Simply remove the callback from the compare
call (see BCrypt with promises:
let isValidPassword = await bcrypt.compare(password,user.password)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论