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
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)