node.js中的callback函数的作用域
我有以下代码:
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 }); };
我的问题是callback函数'done'在第2行中被识别,但在getIssueListcallback中的第6行中是'undefined'。
我如何使它在这个函数中可用,以便我可以传递callback到连续的asynchronous方法?
从参数列表中删除done
:
function(err, response, done) -> function(err, response)
否则,该参数会使用外部函数的相同名称来遮蔽该参数。
你已经在第二个callback中重新定义了一个单独的done
,它将“隐藏”更高范围done
的值。 如果你在第二个callback中删除了done
参数或者命名了不同的东西,那么你可以直接访问更高范围的done.
这是你的代码,第二个callback被重命名为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
,那么你可以从callback声明中删除它。 就个人而言,如果它真的被通过了,我宁愿给它一个不同的名字来承认它是存在的并且可用的,但是你可以使用以下两个选项之一:
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 }); };
当使用像你使用的内联callback时,只要你没有在当前范围中重新定义一个新的variables,那么它允许你访问父范围中的所有variables。 当你重新定义variables(作为局部variables,函数或命名函数参数)时,它将“隐藏”在更高范围内的值,基本上覆盖它,所以你不能达到更高的范围。
因此,访问更高级别范围variables的解决scheme是确保在当前范围内不定义具有相同名称的variables。