Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> }, which means that .then() will not execute correctly. I have been struggling with this problem for some time now and would greatly appreciate any help.

userSchema.methods.verifyPassword = function (password, err, next) {
  const saltSecret = this.saltSecret;
  const a = async function(resolve, reject) {
    console.log('hi4')
    console.log('this.saltSecret2', saltSecret);
    console.log(password);

    const hashed_pass = await bcrypt.hash(password, saltSecret);
    console.log('hash', hashed_pass);
    const valid = await bcrypt.compare(password, hashed_pass);
    if(valid){
      console.log('GOOD');
    }
  };
  a();
};

Answer №1

When it comes to handling promises, I prefer using async-await syntax. Not only is it less confusing, but it also makes it easier to quickly understand someone else's code.

You can turn your function into an async one and await for bcrypt to complete its task.

const password = await bcrypt.hash(password, saltSecret);

Additionally, the bcrypt library offers a function to compare passwords with their hashed counterparts.

const valid = await bcrypt.compare(password, hashed_pass);

Give this code a try:

async function(resolve, reject) {
  console.log('hi4')
  console.log(this.saltSecret);
  console.log(password);

  const hashed_pass = await bcrypt.hash(password, saltSecret);
  console.log('hash', hashed_pass);
  const valid = await bcrypt.compare(password, hashed_pass);
  if(valid){
    console.log('GOOD');
  }
};

Answer №2

Whenever you use this code snippet, it will result in a Promise.

console.log(bcrypt.hash(password, this.saltSecret));

One possible approach to handle this situation is demonstrated below.

return new Promise(async (resolve, reject) => {
    const hash = await bcrypt.hash(password, this.saltSecret);

    if (hash === this.password) {
        return resolve(true);
    }

    return reject();
});

Answer №3

bcrypt.hash utilizes a callback function instead of a promise (which is why it uses .then)

The correct way to use it is as follows:

bcrypt.hash(password, this.saltSecret, (err, hash) => {
    ...
});

Answer №4

How to Encapsulate in a Promise

const createHashedPassword = async (
      passwordToHash: string,
      roundsOfSalt = 10
    ): Promise<{
      salt: string;
      hash: string;
    }> => {
      return new Promise((resolve, reject) => {
        try {
          const salt = bcrypt.genSaltSync(roundsOfSalt);
          return bcrypt.hash(passwordToHash, salt, (error, hash) => {
            if (error) {
              reject(error);
            } else {
              resolve({
                salt,
                hash,
              });
            }
          });
        } catch (err) {
          console.error(err);
          throw err;
        }
      });
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with accessing properties of undefined while trying to post to mongoose with the 'name' field

WARNING: An issue occurred: Cannot read properties of undefined (reading 'name') router.post("/", async (req, res) => { const newItem = new items({ name: req.body.name }) try { const submitted = await items.save(); co ...

What causes my absolutely positioned element to disappear when using overflow-x: hidden?

I've been experimenting with the CSS property overflow-x: hidden on a container and noticed that it causes my element with position: absolute to disappear. To see this effect in action, check out this demo: https://codepen.io/Karina1703/pen/LYMzqEj ...

Looking for help combining HTML5 Canvas and JavaScript to showcase images. Can anyone lend a hand?

I am currently in the process of developing an Android game using HTML5 and Javascript. I have managed to make some progress, but I have encountered a problem that has left me puzzled. Initially, my JS file and Html file were functioning well together for ...

Mongoose parameters do not accept passing an id or element

When working with MongoDB and using mongoose, I attempted to remove an item from a collection by utilizing the findByIdAndDelete() method. However, I encountered the following error: CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f" a ...

Is it possible to incorporate Nth child into JavaScript?

Is it feasible to implement an Nth Child in the following code snippet? $(function() { var count = $(".parent a").length; $(".parent div").width(function(){ return ($(".parent").width()/count)-5; }).css("margin-right","5px"); }); ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...

Microphone Malfunction: Abrupt End of Input Detected

I have been experimenting with SpeechRecognition to incorporate microphone functionality into one of my projects. However, when I check the Chrome Console, it displays the error message: Unexpected end of input const speechRecognition = window.webkitS ...

Using AngularJs to implement a $watch feature that enables two-way binding

I am in the process of designing a webpage that includes multiple range sliders that interact with each other based on their settings. Currently, I have a watch function set up that allows this interaction to occur one way. However, I am interested in havi ...

Creating a mouseover popup window for a specific text citation based on its ID using JavaScript in XSLT

I have implemented the following XML code for citations related to figures, tables, and reference citations. When hovering over the citation, it should display the relevant text based on the id and href. XML code for Citation: Fig. <link href="#ecog34 ...

Journey Through Routes with ES6 Classes

After countless attempts, I've encountered an issue where the code works perfectly in a development environment but fails when running in production, throwing the error TypeError: Router.use() requires middleware function but got Object. I've tri ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

Error in delete operation due to CORS in Flask API

After successfully developing a rest api in Flask and testing all api endpoints with Postman, I encountered an issue while working on an application in Javascript that consumes the resources of my api. The problem lies in consuming an endpoint that uses t ...

Guide to adding a checkbox to a JavaScript list

I'm currently working on building a task list using JavaScript. The concept is to type something into the input field and then, when the user clicks the button, a checkbox with that text will be generated. However, I'm facing an issue as I am no ...

How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving th ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...

Is it possible to activate events on select tags even when they have the disabled attribute?

All the select options on this page have been disabled with an ID that ends in _test, and everything seems to be functioning properly. However, I would like to display a title when the selects are disabled and the mouse hovers over them. The issue arises ...

Tips on creating an onclick function in javaScript and linking it to innerHTML

let a = 10; let b = 15; document.getElementById("text").innerHTML = '<div onclick=\'testing("'a + '","' + b + '") > text </div>'; Welcome, I am new to this ...

The Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...