Home > OS >  node.js - bcrypt.compare() is not working in async function
node.js - bcrypt.compare() is not working in async function

Time:04-11

Here is my code:

async function(account, pwd, done) {
        Member.findOne({ account: account }, (err, user) => {
            if (err) {
                return done(err);
            } else if (await bcrypt.compare(pwd, user.pwd)) {
                return done(null, user);
            } else {
                return done(null, false, { message: 'Password incorrect' });
            }

        });
    }

But when I run the server, I always get this error:

E:\nodeJS\Express\server\routes\api\login.js:22
            } else if (await bcrypt.compare(pwd, user.pwd)) {        
                             ^^^^^^

SyntaxError: Unexpected identifier

Does anyone know how to fix it? Thank you for answering!

CodePudding user response:

Try this:

const bcrypt = require('bcrypt');

bcrypt.compareSync(rawPassword, hashedPassword);

compareSync works for async functions without an await.

CodePudding user response:

I found the solution! Just change the location of async. Here is the solution:

function(account, pwd, done) {
        Member.findOne({ account: account }, async(err, user) => {
            if (err) {
                return done(err);
            } else if (await bcrypt.compare(pwd, user.pwd)) {
                return done(null, user);
            } else {
                return done(null, false, { message: 'Password incorrect' });
            }

        });
    }

Put async in front of (err, user) =>......
Thank again for those who spend time on my question!

  • Related