0
votes

I have a signup user function that I dont really understand how it's working...

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. 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. Anyone can explain me what is really happening?

I understand that await executes code asyncronously...no. await causes your application to wait for code which would otherwise be asynchronous to complete, before continuing to the next line. Without it, the async code would run at the same time as the lines following it. I think you've just got your understanding backwards - ADyson
Some documentation for this? Really trying to understand but still seems like i got it very badly... thanks! - Jigau Rafael
So if I wouldnt use the await keyword, the log would be some pending promise, but using it would actually stop the code at that line and wait for the result... - Jigau Rafael
await pauses the execution of the function until the result it is await for is resolved. - Sachin Ananthakumar
MDN documentation is quite good to understand basic javascript paradigm. Have a look for await here developer.mozilla.org/fr/docs/Web/JavaScript/Reference/… and have a look for asynchronicity with Promises here developer.mozilla.org/fr/docs/Web/JavaScript/Reference/…. - Mathieu Dfr