简体   繁体   English

为什么等待代码在同步代码之前执行?

[英]Why is await code executing before sync code?

I have a signup user function that I dont really understand how it's working...我有一个注册用户 function 我真的不明白它是如何工作的......

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();
        }
    });
}   

} }

So in the last else, I use await bcrypt.hash(password, salt) to encrypt my password.所以在最后,我使用 await bcrypt.hash(password, salt) 来加密我的密码。 I'm new to JS but still I understand that await executes code asyncronously, so console.log(hashedPassword) should not return me the hashed password because this log will execute before the actual hashing.我是 JS 的新手,但我仍然理解 await 异步执行代码,因此 console.log(hashedPassword) 不应返回散列密码,因为此日志将在实际散列之前执行。 Anyone can explain me what is really happening?任何人都可以向我解释到底发生了什么?

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

If you use the await keyword, nodejs will wait for promise to resolve before moving to the next line in the async function. Your console.log's result will be the hashed password.如果您使用 await 关键字,nodejs 将等待 promise 解析,然后再转到异步 function 中的下一行。您的 console.log 的结果将是散列密码。

If you don't use the await keyword, node will start resolving the promise but will not wait for it to finish resolving before moving to next line.如果您不使用 await 关键字,节点将开始解析 promise 但不会等待它完成解析后再移至下一行。 Your console.log's result will be Promise { pending }您的 console.log 的结果将是 Promise { pending }

await executes the code synchronously. await 同步执行代码。 So in your case await will wait for the execution of bcrypt.hash .所以在你的情况下 await 将等待bcrypt.hash的执行。

For more clarity bcrypt.hash function returns a promise and now we have two choices here.为了更清楚bcrypt.hash function 返回promise现在我们在这里有两个选择

1. Await for the promise to resolve 1.等待promise解决

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

the hashedPassword will contain the actual output we need. hashedPassword将包含我们需要的实际 output。

2. Handle promise resolution using then 2. 使用then处理 promise 分辨率

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

As the bcrypt.hash function returns a promise, we need to handle the rest of the code inside a then block as it'll only return the value once the function resolves the promise.由于bcrypt.hash function 返回 promise,我们需要处理 then 块内代码的 rest,因为它只会在 function 解析 promise 后返回值。

In case you want to execute your code asynchronously , you need to remove the await keyword which waits for the promise to resolve before moving to the next line.如果您想asynchronously执行代码,则需要删除等待 promise 解析后再移至下一行的 await 关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM