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

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Is it possible for a Node.js/Express server to securely handle all UTF-8 characters?

At the moment, my setup involves a node server running Express that is connected to a PostgreSQL database with UTF-8 encoding support. In terms of frontend, I'm using Angular which has built-in measures for preventing unsafe injection. I am curious i ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Adjusting the appearance of a JavaScript element based on its hierarchy level

Currently, I am utilizing Jqtree to create a drag and drop tree structure. My main goal is to customize the appearance of the tree based on different node levels. Javascript Tree Structure var data = [ { name: 'node1', id: 1, chi ...

Using NodeJS to establish a DB2 connection pooling system for an Express application

As a newcomer to NodeJS, I am struggling to find information online about integrating IBM DB2 with NodeJS. Specifically, I am facing challenges in setting up connection pooling for my web application. Currently, I am able to run my Node app with a single c ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Dockerhub build process encountering errors with npm install bcrypt causing automated build to fail

I have a Dockerfile setup as follows: FROM ubuntu:14.04 MAINTAINER John Doe <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d28202c24210d20342c3d3d632e2220">[email protected]</a>> ENV NODE_ENV production ...

Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functi ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Is it necessary to decode the JSON data stored in the variable?

Consider the code snippet below: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var responses = JSON.parse(this.responseText); var ...

What are some strategies for optimizing React performance when managing controlled input from numerous components?

Building a Parent component with multiple child components, each passing data to the parent for an API call. The structure is as follows: const MainComponent = () => { const [child1input, setChild1Input] = useState(""); const [child2input, setChild ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

Finding the measurement of a sofa using couch.get(data, headers, status)

After attempting to set up a node.js application with express.js by connecting to couchdb, I utilized the npm package called nodejs-couch. app.get('/', function(req, res) { couch .get(dbName, viewUrl) .then( function(data, heade ...

Dynamic Bootstrap Modal Widget

I have been attempting to create a dynamic modal using Twitter Bootstrap as shown below: $('#myModal').on('hide', function () { $(this).removeData('modal'); $('.loading-modal').remove(); }) Although it rel ...

Nextjs unexpectedly displays blank page upon fetching data from Firebase Firestore without any error messages

I am currently facing an issue when trying to retrieve page details from Firebase Firestore using getStaticPaths and getStaticProps in my Next.js project. Despite following the code structure correctly, I am encountering a scenario where the page appears e ...

After the initial rendering, JQuery can dynamically search through the DOM elements and seamlessly replace keys with their respective values

I am in the process of implementing my personal localization method on my web application that is currently under development. With the use of JQuery 2.2.0 and no other frameworks or third-party tools, I need to embed certain expressions directly into my H ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

Discovering the function invoker when in strict mode

I am facing a challenge in my Angular controller where I have a function called getGames() that can be triggered by both the init() and update() functions. The issue is, I need to handle these two scenarios differently based on which function called getGam ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

In-line Vertical Ticker Display

I attempted to use vTicker, but I found that it does not function properly when used as an inline element. <h1> <div id="vticker"><ul>...</ul></div> Some other headline text </h1> My goal is to have the vertica ...