Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Why is await code executing before sync code?

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

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. Your console.log's result will be Promise { pending }

about 4 years ago · Juan Pablo Isaza Relatório

0

await executes the code synchronously. So in your case await will wait for the execution of bcrypt.hash.

For more clarity bcrypt.hash function returns a promise and now we have two choices here.

1. Await for the promise to resolve

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

the hashedPassword will contain the actual output we need.

2. Handle promise resolution using then

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.

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda