Like the title, in the process of reinventing the wheel, I usebcrypt.compare
on the server side for password verification. I want to modify the global variableinfo
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 isundefined
I tried changinginfo
towindow.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 bindingthis
tocallback
, but here(err, res) => {}.bind( after this)
, it is stillundefined
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)