Home > Software design >  Console Error: await is only valid in async functions and the top level bodies of modules
Console Error: await is only valid in async functions and the top level bodies of modules

Time:05-26

I am making a login functionality in nodejs and there i want to store the password in mysql db by hashing it: I am using bcrypt library.

bcrypt.hash(password, 10, function(err, hash) {
            console.log(hash);
});

Above code working fine for me but if i want to use like below one using await

let hashedPassword = await bcrypt.hash(password,10);

its showing below error as

let hashedPassword = await bcrypt.hash(password,10);
                           ^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules

Note: My aim is to use it in async way so using await. And the doubt is,

  1. is first one works asynchronously
  2. Second one i got from a video and thats working but in my case its not, so whats the issue here

Below is the total controller code for detailed info:

const db = require("../connection");

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

exports.register = (req,res) => {
    const {name, email, password, cpassword} = req.body;

    db.query('SELECT * FROM users WHERE email=?', [email],(error,result)=>{

         if(error){
             console.log(error);
         } else if(result.length > 0){
             return res.render('signup',{
                 message:'Email already exists!'
             })
         } else if(password !== cpassword){
             return res.render('signup',{
                 message: 'Passwords do not match!!'
             });
         }

        let hashedPassword = await bcrypt.hash(password,10);
        console.log(hashedPassword);


        // bcrypt.hash(password, 10, function(err, hash) {
        //     console.log(hash);
        // });
        
    });
}

CodePudding user response:

The basic you have to understand in asynchronous function is to make a function async then use await, but your code there is no asynchronous function for which it will throw error. Hence you have to make the parent function as async type. Updated code below

#previous code..
  db.query('SELECT * FROM users WHERE email=?', [email], async (error,result)=>{
    #other codes here..
    let hashedPassword = await bcrypt.hash(password,10);
    console.log(hashedPassword);
  });

#next code..

This way you can use both ways of hash & salt

CodePudding user response:

your register function is not asynchronous. Try this:

exports.register = async (req,res) => {
    ...rest of the code
}
  • Related