【问题标题】:Scope of a callback function in node.jsnode.js 中回调函数的范围
【发布时间】:2015-11-16 03:55:29
【问题描述】:

我有以下代码:

 exported.removeAllWatchesForUser = function (projectKey, userObj, done) {
   console.log('done='+done); // Function is recognized

    // Get list of all issues & remove the user from watchers list   
    exported.getIssueList(projectKey, function(err, response, done){
                console.log('done='+done); // callback is not recognize but is 'undefined

    });
};

我的问题是回调函数“完成”在第 2 行中被识别,但在 getIssueList 回调中的第 6 行中却是“未定义”。

如何使它在这个函数中可用,以便我可以将调用传递回连续的异步方法?

【问题讨论】:

    标签: javascript node.js callback asynccallback


    【解决方案1】:

    从参数列表中删除done

    function(err, response, done) ->  function(err, response)
    

    否则参数会隐藏与外部函数同名的参数。

    【讨论】:

      【解决方案2】:

      您在第二个回调中重新定义了一个单独的done,它将“隐藏”更高范围的done 的值。如果您在第二个回调中删除 done 参数或将其命名为不同的名称,那么您可以直接访问更高范围的 done.

      这是您将第二个回调重命名为 issueDone 的代码:

      exported.removeAllWatchesForUser = function (projectKey, userObj, done) {
         console.log(typeof done); // Function is recognized
      
          // Get list of all issues & remove the user from watchers list   
          exported.getIssueList(projectKey, function(err, response, issueDone){
                // you can directly call done() here
          });
      };
      

      或者,如果您不打算使用issueDone,那么您可以将它从回调的声明中删除。就个人而言,如果它真的通过了,我宁愿给它一个不同的名字来确认它存在并且可用,但是你可以使用这两个选项之一:

      exported.removeAllWatchesForUser = function (projectKey, userObj, done) {
         console.log(typeof done); // Function is recognized
      
          // Get list of all issues & remove the user from watchers list   
          exported.getIssueList(projectKey, function(err, response){
                // you can directly call done() here
          });
      };
      

      当您使用内联回调时,只要您不在当前范围内重新定义与更高范围内同名的新变量,Javascript 就允许您访问父范围内的所有变量。当您重新定义变量(作为局部变量、函数或命名函数参数)时,它会将值“隐藏”在更高范围内,本质上会覆盖它,因此您无法进入更高范围。

      因此,在更高级别的范围内访问变量的解决方案是确保您没有在当前范围内定义同名的变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多