首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java脚本承诺

Java脚本承诺
EN

Stack Overflow用户
提问于 2021-11-04 05:15:13
回答 2查看 52关注 0票数 2

我想要做的是:

此HTTP调用更新数据库中的密码。我发送了新密码,以便在getHashedPassword()中进行散列和盐化,这是可行的,至少根据打印散列数字的console.log是这样。

问题:当我用promise的结果重新分配body数据字段时,body数据字段没有更新,这在promise之外的控制台日志中得到了证明。因此,在数据库中,新的文字字符串password会更新,但不会更新散列。我会提供输出和图片,以防我的解释令人困惑。

代码语言:javascript
复制
    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' })
            );
        
        });

Console.logs:

代码语言:javascript
复制
new passwords helloagain339
this is the hashed $2b$10$fPw/bHW69mnyltWh0Qn3T.hKIsxbhgTt8/OGxOQXVVRDpTICqZCy.
EN

回答 2

Stack Overflow用户

发布于 2021-11-04 05:26:33

好的,问题是BasicUser.findByIdAndUpdategetHashedPassword promise解析并返回响应之前运行,这样它就可以传递给findByIdAndUpdate。解决方法是使用async/await或将第二个promise放在第一个promise的回调中。

异步/等待方法

代码语言:javascript
复制
router.put("/:id", async (req, res) => {
  try {
    req.body.password01 = await getHashedPassword(req.body.password01);
    console.log("new passwords", req.body.password01);
    const user = await BasicUser.findByIdAndUpdate(req.params.id, req.body);
    res.json({ msg: "Updated successfully" });
  } catch (error) {
    res.status(400).json({ error: "Unable to update the Database" });
  }
});

嵌套回调方法

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2021-11-04 05:27:24

您可以使用async/await使代码更具可读性,如下所示

代码语言:javascript
复制
router.put('/:id', async (req, res) => {
  let result = await getHashedPassword(req.body.password);
  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' }));
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69834767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档