0

Comparing the password on user login request. Used async and await to wait till get the actual response.

I expect it to run on following order 1,2,3,4 (order of console.log)

but it executes as 1, 3, 4, 2. Please help.

script does not wait for comparePassword

async login(request){
        let response =  await User.findOne({ email: request.email }, async (err, user) => {
            if (err) throw err;

            console.log('1');

            let isMatch =  await user.comparePassword(request.password, (err, isMatch) => {
                console.log('2');
                if (err) throw err;
                request.isMatch = isMatch;
            });

            console.log('3');
            return request;

        });

        console.log('4');
        console.log('response', response);
    }
Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71

1 Answers1

5

If you are using async/await, you are using promises, and you must not pass a callback to the mongoose methods. If you don't pass one, they will return a promise that you can await. You are looking for

async login(request){
    let response =  await User.findOne({ email: request.email });
    console.log('1');
    let isMatch =  await user.comparePassword(request.password);
    console.log('2');
    request.isMatch = isMatch;
    console.log('3');
    return request;
    console.log('4');
    console.log('response', response);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Yes, you can put a `try` block around `await`, or use good ol' `.catch()`. See also https://stackoverflow.com/questions/44663864/correct-try-catch-syntax-using-async-await – Bergi Nov 26 '19 at 00:51