函数不返回值:范围问题

需要第二双眼睛…发现有什么不对吗? 我的内在函数不返回值。 我一定在搞范围了吗?

function getGroups(account){ var name; // name = 'assigned'; I work account.getGroups(function(err, groups) { //removed logic for simple debugging name ='test'; //return name; }); return name; } 

当在父函数中分配variables,即var name = 'assigned'它可以工作。

你的account.getGroups可能是一个asynchronous函数,它需要一个callback函数。 这个callback函数,

 function(err, groups) { //removed logic for simple debugging name ='test'; //return name; } 

不会立即执行。 所以你的return name; 语句在你的name = 'test';之前被执行name = 'test'; 声明。

希望这是有道理的。


要从callback中获取更新的值,您必须使getGroupsasynchronous或基于事件

使asynchronous很容易

 function getGroups(account, callback){ var name; // name = 'assigned'; I work account.getGroups(function(err, groups) { //removed logic for simple debugging name ='test'; callback(name); }); } 

而不是调用函数的值(例如,'var groupname = getGroups(account)'),你必须做如下

 getGroup(account, function (groupname){ // do whatever you like with the groupname here inside this function }) 

由于account.getGroups是一个asynchronous函数,您自己的getGroups也被迫为asynchronous。 不要使用return语句return名称,只要将名称传回给callback就可以了:

 function getGroups(account, onDone){ account.getGroups(function(err, groups) { var name ='test'; //... onDone(name); }); } 

用callback代替返回语句编写的代码据说是以连续传递的方式编写的。 你可以谷歌,如果你想要更多的例子。

如果你想传播错误,你可能还想传递一个seconf“error”参数给callback来模仿Nodejs接口。