我对在 node.js 上工作的方式感到很困惑,我说的是回调、返回和源代码的执行方式。
我正在使用sails.js,但我认为它没有关联,我认为这更像是JS的工作方式。
源代码:
module.exports = function (req, res, callback) {
if (req.session.authenticated) {
// Accept user authentication.
return callback();
} else {
// Not authenticated. Try auto authentication.
if(validator.check([validator.rulesHardwareId(req.param('hardwareId'))])){
Device.findOne({hardwareId: req.param('hardwareId')}, function(err, device){
if(err){
return res.json({message: "You are not permitted to perform this action. You have to connect to the platform before. [Wrong hardwareId or DB error]", data: {err: err}, status: false}, 403);
}
if(device){
// Connect the device.
req.session.authenticated = true;
req.session.from = 'device';
// Search for the device's owner.
User.findOne({id: device.userId}, function(err, user){
if(err){
return res.json({message: "DB error.", data: {err: err}, status: false}, 403);
}
if(user){
// Add data about the user.
req.session.user = user;
return callback();
}else{
return res.json({message: "Device found but device's owner doesn't found.", data: {err: err}, status: false}, 403);
}
});
}else{
return res.json({message: "You are not permitted to perform this action. You have to connect to the platform before. [Wrong hardwareId]", data: {err: err}, status: false}, 403);
}
});
}
return res.json({message: "You are not permitted to perform this action. You have to connect to the platform before. [Give hardwareId ?]", data: {}, status: false}, 403);
}
};
代码不是那么重要,问题是我收到了这条消息:“您不允许执行此操作。您必须先连接到平台。[Give hardwareId ?]”
但是动作是创建的。好的,所以我调用 callback() 并返回它,但源代码继续吗?并执行最后一行?为什么?我不明白。如果我将最后一行放在 ELSE 中,我会收到消息“操作已创建”。
如果有人可以解释我.. 我认为添加 return 关键字对于防止这种情况很有用,但看起来我错了。
谢谢你。