0

i have a class for hash data in nodejs .

this is my class :

const bycrypt = require("bcrypt");
module.exports = new (class Utilitie {
  HashField(field) {

    return new Promise((resolve, reject) => {
      bycrypt.hash(field, bycrypt.genSaltSync(15), (error, hash) => {
        if (error) return reject(error);
        resolve(hash);
      });
    });
  }
})();

and this is my controller for use this class for hash data :

    async ResetPassword(req, res, next) {
    const result = await this.ValidationAction(req, res);
    if (result[0]) {
      let user = await User.findOne({ userName: req.body.userName }).then(
        (user) => {
          if (!user) return this.Notfound(res);
          user.password = Utilite.HashField(req.body.password).then(
            (error, hash) => {
              console.log("in controller", hash);
            }
          );
          user.save();
        }
      );
      this.Ok(res);
    }
    return this.BadRerquest(res, result[1]);
  }

but it not hash field and it return the undefined .

whats the problem ? how can i solve this problem ????

kianoush dortaj
  • 411
  • 7
  • 24
  • 2
    Read the documentation of [Promise#then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) and learn how to [return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – str Jul 04 '20 at 18:11
  • [Avoid the anonymous `class` antipattern](https://stackoverflow.com/q/38739499/1048572)! Your first snippet can be shortened to two lines: `const bycrypt = require("bcrypt"); module.exports.HashField = field => bycrypt.hash(field, bycrypt.genSaltSync(15));` given that *bcrypt* supports promises natively. – Bergi Jul 04 '20 at 18:19

1 Answers1

0

The argument that your then callback receives will be the hash value. The return value of the then() call will be another promise. You meant to use await:

async ResetPassword(req, res, next) {
  const result = await this.ValidationAction(req, res);
  if (result[0]) {
    const user = await User.findOne({ userName: req.body.userName });
    if (!user) return this.Notfound(res);
    user.password = await Utilite.HashField(req.body.password);
//                  ^^^^^
    await user.save();
    this.Ok(res);
  } else {
    this.BadRerquest(res, result[1]);
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375