Javascript 未在特定块外定义变量
我试图修改我的代码(在passport函数中),以便它从mongodb数据库而不是数组中读取值 我最初的工作代码如下:Javascript 未在特定块外定义变量,javascript,node.js,mongodb,express,passport.js,Javascript,Node.js,Mongodb,Express,Passport.js,我试图修改我的代码(在passport函数中),以便它从mongodb数据库而不是数组中读取值 我最初的工作代码如下: passport.use( new LocalStrategy( { usernameField: "email", passwordField: "userName" }, (email, variable, done) => { let use
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模块中完成的,这里称为mongoUtil模块,工作正常):
但是,用户值未在使用它的块之外定义。既然我已经在函数中的块之前声明了值,为什么不在有问题的块之外定义它呢?mongodb回调之外的用户变量没有设置,因为
db.collection('Users').findOne({email}
返回一个承诺
回拨后的代码将在回拨返回值之前执行“但是用户值未在使用它的块之外定义”-函数,而不是块。我明白了。有意义。谢谢Sven.hig。
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'})
}
}
)
)