You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript Promise异步执行导致req.body密码哈希赋值不生效问题

问题原因

这是JavaScript异步执行逻辑导致的顺序问题:

  • getHashedPassword() 返回Promise属于异步任务,你传入.then()的回调函数不会立刻执行,会等哈希计算完成后才会被调度执行
  • 你的控制台输出顺序也能印证这个执行逻辑:先打印了明文密码,后打印了哈希计算结果
  • 你当前的代码会先按顺序执行getHashedPassword()、打印明文密码、调用数据库更新逻辑,最后才会执行.then()里的哈希值赋值操作,所以赋值完全不会作用到数据库更新的参数里,自然存的是明文。
修复方案

方案1:把后续逻辑放到.then()回调内

把密码赋值、数据库更新的逻辑都放到getHashedPassword()的.then()回调里,保证拿到哈希值之后再执行后续操作:

router.put('/:id', (req, res) => {
  getHashedPassword(req.body.password01).then(result => {
    console.log('this is the hashed', result);
    req.body.password01 = result;
    console.log('new passwords', req.body.password01);
    BasicUser.findByIdAndUpdate(req.params.id, req.body)
      .then(user => res.json({ msg: 'Updated successfully' }))
      .catch(err =>
        res.status(400).json({ error: 'Unable to update the Database' })
      );
  })
});

方案2:用async/await简化异步写法,可读性更高

把路由回调改成async函数,用await等待异步任务完成再往下执行,写法和同步逻辑接近:

router.put('/:id', async (req, res) => {
  try {
    const hashedPwd = await getHashedPassword(req.body.password01);
    console.log('this is the hashed', hashedPwd);
    req.body.password01 = hashedPwd;
    console.log('new passwords', req.body.password01);
    await BasicUser.findByIdAndUpdate(req.params.id, req.body);
    res.json({ msg: 'Updated successfully' });
  } catch (err) {
    res.status(400).json({ error: 'Unable to update the Database' });
  }
});

内容的提问来源于stack exchange,提问作者notacoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:45:04