search

Home  >  Q&A  >  body text

javascript - bcrypt.compare is used to verify passwords in Meteor. How to modify global variables in the callback function?

Like the title, in the process of reinventing the wheel, I use bcrypt.compare on the server side for password verification. I want to modify the global variable info in the callback function. How to achieve this?
The code I wrote is as follows:

Meteor.methods({
    userLogin: (username, password) => {
        let user = Users.find({username: username}).fetch()[0];
        let info;
        bcrypt.compare(password, user.password, (err, res) => {
            if (err) {
               info = {
                    status: 0,
                    data: err
                }
            }
            // res == true 输入的密码与保存的密码一致
            if (res) {
                info = {
                    status: 1,
                    data: [{
                        _id: user._id,
                        username: user.username,
                        group: user.group
                    }]
                };
            } else {
                info = {
                    status: 0,
                    data: "username or password invalid"
                };
            }
        });
        console.log(info);

        return info;
    }
});

console.log(info);The printed content is undefined

I tried changing info to window.info (ps: I found the solution online, I don’t know why I did this), but it reported an error directly. I was writing react before. A similar situation was encountered when using the component, which was solved by binding this to callback, but here (err, res) => {}.bind( after this), it is still undefined

过去多啦不再A梦过去多啦不再A梦2752 days ago852

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:47:27

    bcrypt.compare is an asynchronous method. When you console.log, info has not been assigned a value. In this case, you should change your method to an asynchronous method, let userLogin return Promise, and then resolve( after bcrypt is completed. info)

    reply
    0
  • Cancelreply