【问题标题】:Node.js callback functionalityNode.js 回调功能
【发布时间】:2014-01-18 10:24:27
【问题描述】:

我是 Node.js 平台的新手,我正在努力学习。在玩过回调之后,一件事真的让我很困惑:

所以,我有这个功能:

    function registerUser(body, res, UserModel){

    var userJSON =  {
        email : body.email,
        password : body.password,
        accessToken : null
    };
    var user = null;
    var userAlreadyExists = false;

    UserModel.find({}).select('email').exec(function(err, results){
        if(err){
            console.log('Database error : ' + err);
         // send the appropriate response

        }else{
            for(var index in results){
                if(results[index].email == userJSON.email){
                    userAlreadyExists = true;
                    break;
                }
            }
            if(userAlreadyExists){
                // send the appropriate response
            }else{
                  newAccessToken(UserModel, function(error, token){
                    if(error != null){
                           // handle the error
                    }else{
                        userJSON.accessToken = token;
                        user = new UserModel(userJSON);
                        user.save(function(err){
                            if(err){
                               // .. handle the error
                            }else{
                               // .. handle the registration
                            }
});}});}}});}

然后是接受回调的函数:

function newAccessToken(UserModel, callback){

    UserModel.find({}).select('email accessToken').exec(function(err, results){
        if(err){
            callback(err, null);
        }else{
          // .... bunch of logic for generating the token
            callback(null, token);
        }

    });
}

我希望回调不起作用(可能会引发错误),因为 useruserJSON 都没有在它的上下文中定义。(嗯,这并不完全正确,但因为它是异步执行的 - 在而 - ,我希望回调丢失它对那些变量的引用,这些变量是在 registerUser 函数中本地定义的)。相反,这个例子完美地工作,回调函数保持它的引用与registerUser 函数中定义的这两个变量。有人可以解释一下异步回调和引用是如何工作的,以及为什么这个例子有效吗?

【问题讨论】:

    标签: javascript node.js callback mongoose


    【解决方案1】:

    那些称为闭包而不是回调,在 JavaScript 中,作用域处理是特殊的。检查此文档:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

    【讨论】:

    • 所以闭包保持它的引用与主函数中定义的变量,即使闭包在一段时间后执行,例如 1 分钟?
    • 是的,不用担心时间,函数是在调用函数的范围内执行的。
    【解决方案2】:

    您好,您“回调”的函数是您尝试访问的变量的范围内,因此可以访问它们。

    这不是 nodejs 的事情,普通 JS 的工作方式是一样的。

    区别

    1) 将无法访问名为 'foo' 的变量

    function finishfunction() {
      console.log(foo); /*  undefined */
    }
    
       function functionwithcallback(callback) {
           callback();
      }
    
      function doStuff() {
    
         var foo = "bar";
    
        functionwithcallback(finishfunction);
    
     }
    
     doStuff();
    

    2) 像你一样,访问 'foo' 很好。

       function functionwithcallback(callback) {
           callback();
      }
    
      function doStuff() {
    
         var foo = "bar";
    
        functionwithcallback(function() {
    
        console.log(foo) /* all fine */
    
        });
    
     }
    
     doStuff();
    

    【讨论】:

    • 例如,即使闭包在 5 分钟后执行,它仍然会保留对这些变量的引用?
    • 是的,所有内容都在范围内。试一试。顺便说一句,我将这些称为常规回调(一个定时函数在完成时被“回调”)。闭包(函数中的函数)最好用方法和私有变量为对象(函数)命名,并从多个来源更新对象(函数)的私有范围变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多