我们如何让代码等待执行 node.js 中的下一条语句

how we make code to wait to execute next statement in node.js

我有 node.js 下面提到的代码:

    router.post("/addData", async (req, res)=>{
      const password = req.body.password;
      console.log("before.password: ", password);
      await bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(password, salt, (err, hash) => {
          if (err) {
            console.log("bcrypt error: ", err);
          }
          console.log("hash passw: ", hash);
          password = hash;
        });
      });
      console.log("after.password: ", password);
});

实际输出为:

before.password: passw 
after.password: passw 
hash passw:  a$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG

我需要如下所示的预期输出:

before.password: passw 
hash passw:  a$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG 
after.password: a$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG

当从 bcrypt 块中打印密码时,我们得到的是未经过哈希处理的纯密码,我知道 bcrypt 正在运行并且密码已成功哈希处理,但我们无法从 bcrypt 块中获取经过哈希处理的密码。

请帮我解决同样的问题,我想我在某些时候放错了代码。提前致谢。

您正在使用两种方法来处理异步代码。当你这样做时

bcrypt.genSalt(10, (err, salt) => { 
  // callback code here
})

您正在使用回调。回调是在 genSalt 函数完成时执行的函数。所以你告诉程序:"when genSalt has finished run this code"

另一种处理异步代码的方法是使用 async/await 的承诺。所以基本上你说:"wait for this and return me the value"

const hash = await bcrypt.genSalt(10) // waiting for promise, no callback.

在您的代码中,您同时执行了两个版本。

另请注意,bcrypt 也有 genSaltSynchashSync 方法。所以你可以这样做:

router.post("/addData", (req, res)=>{
      const password = req.body.password;
      console.log("before.password: ", password);
      const salt = bcrypt.genSaltSync(10);
      const hash = brypt.hashSync(password,salt)
      console.log("after.password: ", hash);
});

请注意,在此示例中,处理程序没有 async 关键字。由于我们使用的是同步方法。