简体   繁体   中英

Can't return data out of the bcrypt.compare() function in nodejs with promises

I'm currently buildung an application with nodejs (10.15.2) but I'm running into some problems with the login function.

Snippet from my "dbconnector.js" file:

login(email, password) {
    return userModel.findOne({
      email: email
    }).lean().then(function(user) {
      // return user;
      return bcrypt.compare(password, user.password, function(err, res) {

           if (res) {
              console.log(user); //prints the userinfo - works fine
              return user;
          }
        });
    });
};

Snippet from my serve.js file:

app.post('/login', async (req, res) => {

    var { email, password } = req.body;
    var user = await dbconnector.login(email,password);
    console.log(user) //returns undefined

    if (user != false) {
      console.log("loggedin");
        const accessToken = jwt.sign({ email: user.email,  id: user.id }, key.tokenKey);

        res.json({
            accessToken
        });
    } else {
        res.send('Username or password incorrect');
    }
});

My problem is that the login() -function returns undefined. However, when I change it to the following, it works perfect (just without checking the password...):

  login(email, password) {
    return userModel.findOne({
      email: email
    }).lean().then(function(user) {
    return user;
    });
};

So I know something's wrong with the bcrypt / promise part but I couldn't find a solution.

My Fellow brother, the problem lives in the fact that a promise will only return you another promise and the compare callback that you have there as its name says callback is not apromise. Lets make it a promise


login(email, password) {
    return userModel.findOne({
      email: email
    }).lean().then(function(user) {
      // return user;
      return new Promise((resolve, reject) => {
          return bcrypt.compare(password, user.password, (err, res) => {
              if (err) {
                  return reject(err);
              }

              return resolve(res);
        })
};

BUT!!! if by any means the bcrypt package u are using is this one https://www.npmjs.com/package/bcrypt then you dont event have to promisify the method, it has it as promise already


login(email, password) {
    return userModel.findOne({
      email: email
    }).lean().then(function(user) {
      return bcrypt.compare(password, user.password);
    }).then(isEquals => {
        if (isEquals) {
            return true
        }

        return false
    }).catch(error => {
        throw error;
    })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM