了解Node.js处理顺序 [英] Understanding Node.js processing order
问题描述
我在理解Node.js中的处理顺序时遇到问题。
我的问题:
我编写了一个小应用程序,它将会话保存在具有以下属性的cookie中:
I'm having problems understanding the processing order in Node.js. My Problem: I coded a little Application that saves a session in a cookie with the following properties:
session.email = email;
session.randomHash = randomHash;
randomHash var是一个随机String,每次用户登录时都会生成并保存到db。
如果现在有会话的用户想要查看私人页面,则调用方法checkSession():
The randomHash var is a random String that gets generated and saved to a db everytime the user logs in. If a user with a session now wants to view a private page the method checkSession() gets called:
exports.checkSession = function(req, res) {
if(req.session) {
var User = mongoose.model("User", userSchema);
User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
if(count === 0) {
return false;
}
if(count === 1) {
return true;
}
});
}
else {
return false;
}
};
该方法将cookie的randomHash与Db的randomHash值进行比较。
此方法在路径中调用:
The method compares the randomHash of the cookie with the randomHash value of the Db. This method is called in a route:
exports.init = function(req, res) {
if(hashing.checkSession(req, res)) {
res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
}
else {
res.send("Sorry but you are not logged in. Go to /login");
}
};
现在一定有问题。
由于Nodes非阻塞样式,方法被调用但在if语句执行之前没有完成。
我该怎么办?
Now there must be the problem. Because of Nodes non-blocking style the method gets called but doesn't finish before the if-statement is executed. What can i do about it?
推荐答案
返回
User.count
回调中的值不是的
。 返回
值checkSession User.count
回调直到 <$ em> <$ em $ c> c> checkSession 完成后才会运行。
The return
value in your User.count
callback is not the return
value of checkSession
. The User.count
callback doesn't run until after checkSession
has finished.
将回调传递给 checkSession
并在 User.count
:
exports.checkSession = function(req, res, callback) {
if(req.session) {
var User = mongoose.model("User", userSchema);
User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
if(count === 0) {
callback(false);
}
if(count === 1) {
callback(true);
}
});
}
else {
callback(false);
}
};
并称之为:
exports.init = function(req, res) {
hashing.checkSession(req, res, function(result) {
if(result) {
res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
}
else {
res.send("Sorry but you are not logged in. Go to /login");
}
});
};
这篇关于了解Node.js处理顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!