0
import bcrypt from 'bcrypt';

export default class Hash {
 static hashPassword (password: any): string {

   let hashed: string;

    bcrypt.hash(password, 10, function(err, hash) {
      if (err) console.log(err);
      else {
        hashed = hash;
      }

    });
    return hashed;
   }


}

this function returns undefined everytime

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Michael
  • 15
  • 1
  • 5
  • Can you `console.log(bcrypt.hash)` and see what's returned? Also how are you importing bcrypt in your file? – Stretch0 Apr 03 '18 at 13:48
  • yes, I am importing bcrypt, I forgot to add it.If I console.log(hash) from within the scope it returns the hashed password, but when I console.log(hashed) it returns undefined – Michael Apr 03 '18 at 13:50
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Aluan Haddad Apr 03 '18 at 13:54

1 Answers1

1

the hash function has not finished when you return hashed.

You want to handle your hashed password within the callback function itself or handle an asynchronous function as Aluan pointed out.

One way to do that is use a promise

export default class Hash {

    return new Promise((resolve, reject) => {
        static hashPassword (password: any): string {

       let hashed: string;

        bcrypt.hash(password, 10, function(err, hash) {
          if (err) reject(err);
          else {
            resolve(hash);
          }

        });
       }
    })

}

Then when you want to call hash, call it as a promise

Hash.then(hashed => {
    console.log(hashed)
}).catch(err => {
    console.log(err)
})
Stretch0
  • 8,362
  • 13
  • 71
  • 133