javascript - Node.js 返回、回调和源码执行流程——运行时

标签 javascript node.js callback runtime sails.js

我对在 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);

    }
};

代码不是那么重要,重要的是我收到了这条消息: “您无权执行此操作。您必须先连接到平台。[提供硬件 ID?]”

但 Action 已创建。好的,所以我调用了 callback() 并返回了它,但是源代码继续?并执行最后一行?为什么?我不明白。 如果我将最后一行放在 ELSE 中,我会收到消息“操作已创建”。

如果有人可以解释我..我认为添加 return 关键字对于防止这种情况很有用,但看起来我错了。

谢谢。

最佳答案

当您像您的代码一样发出异步请求时,执行流程不会等待响应。它只是继续前进,就好像没有什么可以阻止它一样(因为那里没有任何东西)。所以你的主要功能立即返回。

您提供的嵌套 return 语句正在向那些嵌套函数的调用者返回一个值。那么来电者是谁?好吧,您将这些函数作为参数传递给一些内部代码,因此内部代码是调用者,并且该内部代码可能不关心 return 值。

所以这意味着所有这些 return 语句都没有做任何有用的事情,因为您的主函数已经返回,并且调用您的函数的代码忽略了它们。

那你是做什么的?好吧,如您所见,您收到了一个 callback 函数,该函数被传递给您的 module.exports 函数。因此,您应该做的是将通常返回 的数据作为参数传递给回调。然后作为 callback 传递的任何函数都将接收该数据,并用它做任何你想做的事。

module.exports = function (req, res, callback) {
    if (req.session.authenticated) {
        // Accept user authentication.
        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) {
                    callback(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));
                } else 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) {
                            callback(res.json({message: "DB error.", data: {err: err}, status: false}, 403));
                        } else if (user) {
                            // Add data about the user.
                            req.session.user = user;
                            callback();
                        } else {
                            callback(res.json({message: "Device found but device's owner doesn't found.", data: {err: err}, status: false}, 403));
                        }
                    });
                } else {
                    callback(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));
                }
            });
        } else {
            callback(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));
        }
    }
};

所以你的函数会像这样被调用:

 // This is the callback ------v
my_module(the_req, the_res, function(err) {
    if (err) {
        // do something with the error
        console.log(err);
    }
});

关于javascript - Node.js 返回、回调和源码执行流程——运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284145/

相关文章:

javascript - Nodejs AWS Lambda 切换到另一个帐户访问权限和 key 以执行功能

javascript - Jquery 自定义函数与 CallBack

javascript - Async.waterfall 的 native 回调函数

c++ - 如何在宏 BranchCallback 中修复边界/更改变量边界? C++

javascript - POST 请求仅在服务器启动后第二次有效

javascript - 从数组中的 JSON 对象内部获取记录

javascript - 没有 Alpha channel 的 Canvas toDataURL

javascript - Grunt Uglify 获取节省的空间总和

javascript - 在任何给定时间仅允许 Backbone 集合中的一个模型具有事件属性

javascript - 无法读取未定义的不一致嵌入的属性 'includes' 来检测表情符号