javascript - 未在特定块外定义的变量
问题描述
我正在尝试修改我的代码(在护照函数中),以便它从 mongodb 数据库而不是从数组中读取值。
我最初的工作代码如下:
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "userName"
},
(email, variable, done) => {
let user = users.find((user) => {
return user.email === email
})
if (user) {
done(null, user)
} else {
done(null, false, { message: 'Incorrect username or password'})
}
}
)
)
修改后的代码(与最初的代码相同,除了实际从 mongodb 获取值的代码)如下(与 mongodb 的实际连接是在 mongoUtil 模块中完成的 - 在此处调用 - 并且正在工作美好的):
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "userName"
},
(email, variable, done) => {
var user
mongoUtil.connectToServer(function(err, client) {
var db = mongoUtil.getDb()
db.collection('Users').findOne({email}, function(err, result) {
user = result
return user.email === email
})
})
if (user) {
done(null, user)
} else {
done(null, false, { message: 'Incorrect username or password'})
}
}
)
)
但是,用户值未在使用它的块之外定义。既然我已经在函数内的块之前声明了值,为什么没有在相关块之外定义它?
解决方案
未设置 mongodb 回调之外的用户变量,因为
db.collection('Users').findOne({email}
返回一个承诺,并且回调之后的代码将在您的回调返回值之前执行
推荐阅读
- css - 如何在反应中导入CSS文件路径而不是整个文件
- c++ - 如何将元素从 std::list 复制到结构数组?
- javascript - Chart.js 雷达图表图例标签字体大小不起作用
- json - 字典到 JSON 字符串
- python - Python:重采样和前向填充到最近一个月
- graph - 如何将表格导出为 png 文件?
- python - 无法从 JWT 导入 TokenObtainPairView、TokenRefreshView
- javascript - 如何让 Chrome 扩展程序休眠一段时间并在端口上发布消息
- python - 优化大型excel文件的处理
- javascript - 如何使用javascript为每个表行打印不同的值