dcodeIO / bcrypt.js

Optimized bcrypt in plain JavaScript with zero dependencies.
Other
3.47k stars 264 forks source link

Async functions returning undefined #67

Closed m8r1x closed 6 years ago

m8r1x commented 6 years ago

I'm not sure if I'm doing this right but every async function I use keeps on returning null. Here is my sample code:

var bcrypt = require('bcryptjs');

var password = bcrypt.hash('thisispassword', 12, function(err, hash){
    if(err) throw new Error(err);
        return hash; 
});

console.log(password); // output: undefined

Any tips or help on how to handle this would be appreciated.

dcodeIO commented 6 years ago

That's why it's called an asynchronous function. The result is provided to the callback once it becomes available. It isn't returned synchronously.

m8r1x commented 6 years ago

I get what you mean but how would you suggest I use it? I'm trying to use it in a web app to hash passwords before storing them in the database but I always get undefined which, in my case, means that the users's information does not get stored in the database as the password field is marked required.

uttampawar commented 6 years ago

@m8r1x You can use it two ways. Following are examples from bcryptjs documentation, 1) Sync way var bcrypt = require('bcryptjs'); var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync("B4c0/\/", salt); console.log(hash); //Store this in the db.

2) Async way var bcrypt = require('bcryptjs'); bcrypt.genSalt(10, function(err, salt) { bcrypt.hash("B4c0/\/", salt, function(err, hash) { // Store hash in your password DB. console.log(hash); }); });

m8r1x commented 6 years ago

Oh! S#!+... Never mind I see my issue now. Thanks for your help and sorry for the inconvenience :-)