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);
    }
2
  • 1
    await user.comparePassword is executing asynchronously. Can you show your comparePassword method? Commented Sep 3, 2018 at 12:47
  • thanks found the issue, you saved my day Commented Sep 3, 2018 at 12:50

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you can put a try block around await, or use good ol' .catch(). See also stackoverflow.com/questions/44663864/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.