Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise returning undefined in nodejs

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading