【问题标题】:Why is await code executing before sync code?为什么等待代码在同步代码之前执行?
【发布时间】:2021-11-21 13:37:52
【问题描述】:

我有一个注册用户功能,但我不太明白它是如何工作的......

module.exports.signupUser = async (req, res) => {
let email = req.body.email;
let password = req.body.password;
if(!validator.isEmail(email))
{
    res.status(400).json({
        "message": "Please enter a valid email!"
    }).end();
}
else if(!validator.isLength(password, {min:6})){
    res.status(400).json({
        "message": "Password must have at least 6 characters!"
    }).end();
}
else {
    const salt = bcrypt.genSaltSync(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    let params = [email, hashedPassword];
    console.log(hashedPassword);

    let query = 'insert into users (email, password) values (?,?)';
    connection.query(query, params, (err, result, fields) => {
        if(err && err.code === 'ER_DUP_ENTRY') {
            res.status(400).json({
                "message": "There is an account already associated with this email adress!"
            }).end();
        }
        else {
            res.status(200).json({
                "message": "User created!"
            }).end();
        }
    });
}   

}

最后,我使用 await bcrypt.hash(password, salt) 来加密我的密码。 我是 JS 新手,但我仍然了解 await 异步执行代码,因此 console.log(hashedPassword) 不应该返回我散列密码,因为此日志将在实际散列之前执行。谁能解释一下到底发生了什么?

【问题讨论】:

  • I understand that await executes code asyncronously...没有。 await 会导致您的应用程序在继续执行下一行之前等待异步完成的代码。没有它,异步代码将与它后面的行同时运行。我认为你的理解倒退了
  • 这方面的一些文档?真的很想理解,但似乎我理解得很糟糕......谢谢!
  • 所以如果我不使用 await 关键字,日志将是一些未决的承诺,但使用它实际上会停止该行的代码并等待结果...
  • await 暂停 function 的执行,直到它是 await 的结果被解析。
  • MDN 文档非常适合理解基本的 javascript 范例。在此处查看 await developer.mozilla.org/fr/docs/Web/JavaScript/Reference/… 并在此处查看与 Promises 的异步性 developer.mozilla.org/fr/docs/Web/JavaScript/Reference/…

标签: javascript node.js async-await


【解决方案1】:

await 同步执行代码。所以在你的情况下 await 将等待 bcrypt.hash 的执行。

为了更清楚,bcrypt.hash 函数返回一个promise,现在我们在这里有两个选择

1。等待承诺解决

const hashedPassword = await bcrypt.hash(password, salt);
console.log(hashedPassword);

hashedPassword 将包含我们需要的实际输出。

2。使用then 处理承诺解决方案

bcrypt.hash(password, salt).then(hashedPassword => {
    console.log(hashedPassword);
})

由于bcrypt.hash 函数返回一个promise,我们需要处理then 块中的其余代码,因为它只会在函数解析promise 时返回值。

如果你想执行你的代码asynchronously,你需要删除 await 关键字,它等待承诺解决,然后再移动到下一行。

【讨论】:

    【解决方案2】:
    const hashedPassword = await bcrypt.hash(password, salt);
    console.log(hashedPassword);
    

    如果您使用 await 关键字,nodejs 将等待 promise 解决,然后再移动到 async 函数的下一行。 您的 console.log 的结果将是哈希密码。

    如果你不使用 await 关键字,节点将开始解析承诺,但不会等待它完成解析,然后再移动到下一行。 您的 console.log 的结果将是 Promise { pending }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2020-07-02
      • 2015-06-02
      • 1970-01-01
      • 2020-06-20
      • 2014-12-03
      • 2021-09-01
      相关资源
      最近更新 更多