使用 await 后散列密码不起作用

Hashing password not working after using await

我试图在更新密码后对其进行哈希处理,但我不明白为什么它只是在等待行之后才起作用。在 res.json 中,我得到了散列密码,但就在那里。 我是新手,所以非常感谢任何帮助或建议。

router.put('/:id', async (req, res) => {
let { mail, password } = req.body;

bcrypt.genSalt(saltRounds, function (err, salt) {
if (err) return next(err);

bcrypt.hash(password, salt, function (err, hash) {
  if (err) return next(err);
  password = hash;
});
});

const newUser = { mail, password };
await User.findByIdAndUpdate(req.params.id, newUser);
res.json({ mensaje: `Updated Password ${password}` });
});

根据我的评论,您应该更多地研究 async/await 和回调以了解调用顺序。因为它不是您认为的顺序方式的 运行 。但您可以尝试以下方法。

router.put('/:id', async (req, res) => {
  let { mail, password } = req.body;
  try{
    const salt = await bcrypt.genSalt(saltRounds);
    const hashedPassword = await bcrypt.hash(password, salt);
    const newUser = { mail, password };
    await User.findByIdAndUpdate(req.params.id, newUser);
    res.json({ mensaje: `Updated Password ${password}` });
  } catch(error) {
    res.json(error);
  }
});