Home > Net >  Where is the result of async function in node app?
Where is the result of async function in node app?

Time:09-27

So i'm trying to build some basic signup on the backend side with nodejs and MySQL.

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

My problem is when I use the bcrypt.hash function, I dont know how to get the hashed password because the function returns me a promise. So how I access the hashed password so later I can introduce it in my db? I know I can use promise.then() but still don't have an idea about what to do after to get my password. Any ideas, this seems easy but still I am not smart enough

CodePudding user response:

You should use await or Use bcrypt.hashSync() method instead of bcrypt.hash(),

const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);

//or

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

Refer Doc: https://www.npmjs.com/package/bcrypt

  • Related