0

So my problem is that I can't get a value from an exported async function.

This is my function in userInterface :

    exports.login = async (email, password) => {
        return await User.findOne({email})
            .then((user, err) => {
                return bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) { return err; }
                    if(isMatch) { 
                        return jwt.sign({user}, 'privatekey', { expiresIn: '1h' }); 
                    } else { return 'Error: Could not log in password is incorrect'; }
                });
            })
            .catch((e) => { throw Error('Error: Could not log in email is incorrect') })
}

I call this from an other function (userController) :

exports.login = async (req, res, next) => {
    const { email, password } = req.body.object;
    try {
        const token = await userInterface.login(email, password)
        return res.status(200).json({ status: 200, data: token, message: "Succesfully User Login" });
    } catch (e) {
        return res.status(400).json({ status: 400, message: e.message });
    }    
}

But the value of the token is still not defined while in userInterface I can retrieve it.

Thank you for help guys !

kuni
  • 1
  • 1
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Jul 27 '20 at 12:29
  • Thanks for your answer, but even after reading the article i don't understand why a return outside the bcrypt.compare() function works but not inside. – kuni Jul 27 '20 at 14:41

1 Answers1

0

SOLUTION :

bcrypt has a compareSync() function which does much the same as compare(), but asynchronously.

kuni
  • 1
  • 1