您的位置:首页技术文章
文章详情页

javascript - Meteor 中使用 bcrypt.compare 验证密码,如何在回调函数中修改全局变量?

【字号: 日期:2023-09-11 18:38:02浏览:69作者:猪猪

问题描述

如题,自己造轮子的过程中,在服务器端利用 bcrypt.compare 做密码验证,想在回调函数中来修改全局变量 info,如何实现?自己写的代码如下:

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);打印的内容为 undefined

尝试过将 info 改成 window.info (ps:网上找到解决方案,我也不知道为什么要这样做), 但直接报错,之前在写 react 组件时也遇到类似的情况,通过给 callback 绑定 this 解决的,但在这里给(err, res) => {}.bind(this)后,依旧是 undefined

问题解答

回答1:

bcrypt.compare 是一个异步方法,你console.log的时候,info还没有被赋值,这种情况下你应该把你的方法也改成异步方法,让userLogin返回Promise,然后在bcrypt完成以后resolve(info)

标签: JavaScript