Promise 在 Node.js 中返回 undefined。

huangapple go评论89阅读模式
英文:

Promise returning undefined in nodejs

问题

以下是翻译后的代码部分:

  1. const express = require('express');
  2. const bcrypt = require('bcrypt');
  3. let salt;
  4. const loginUser = async (req, res) => {
  5. const { email, password } = req.body;
  6. try {
  7. let user = await userModel.findOne({ email });
  8. salt = await bcrypt.genSalt(10);
  9. if (!user) return res.status(400).json("用户名或密码无效");
  10. let validStatus = false;
  11. let isValidPassword = await bcrypt.compare(password, user.password, (err, result) => {
  12. // console.log(err);
  13. console.log(result);
  14. if (result) validStatus = true;
  15. });
  16. console.log(validStatus);
  17. if (!isValidPassword) return res.status(400).json("用户名或密码无效");
  18. const token = createToken(user._id);
  19. res.status(200).json({ _id: user.id, name: user.name, email, token });
  20. } catch (err) {
  21. console.log(err);
  22. }
  23. };

希望这对你有帮助。如果需要进一步的帮助,请随时提问。

英文:

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

  1. const express=require('express');
  2. const bcrypt=require('bcrypt');
  3. let salt;
  4. const loginUser=async (req,res)=>{
  5. const {email,password}=req.body;
  6. try{
  7. let user=await userModel.findOne({email});
  8. salt= await bcrypt.genSalt(10);
  9. if(!user) return res.status(400).json("invalid Username or passowrd");
  10. let validStatus=false;
  11. let isValidPassword = await bcrypt.compare(password,user.password,(err,result)=>{
  12. // console.log(err);
  13. console.log(result);
  14. if(result) validStatus=true;
  15. });
  16. console.log(validStatus);
  17. if(!isValidPassword) return res.status(400).json("invalid Username or passowrd");
  18. const token=createToken(user._id);
  19. res.status(200).json({_id:user.id,name:user.name,email,token});
  20. }
  21. catch(err)
  22. {
  23. console.log(err);
  24. }
  25. };

答案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):

  1. 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:

  1. let isValidPassword = await bcrypt.compare(password,user.password)

huangapple
  • 本文由 发表于 2023年6月29日 01:14:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定