【问题标题】:Function is not returning value: scope issue [duplicate]函数没有返回值:范围问题[重复]
【发布时间】:2014-07-01 00:22:56
【问题描述】:

需要第二双眼睛...发现这有什么问题吗?我的内部函数没有返回值。我一定是把范围弄乱了?

 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;
}

在父函数(即var name = 'assigned')中分配变量时,它可以工作。

【问题讨论】:

    标签: javascript node.js scope


    【解决方案1】:

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

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

    不会立即执行。因此,您的 return name; 语句会在您的 name = 'test'; 语句之前执行。

    希望这是有道理的。


    要从回调中获取更新的值,您必须使 getGroups 异步或基于事件

    制作异步很容易

    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
    })
    

    【讨论】:

    • 确实如此。但是,我如何构建它以维护具有所需返回结果的良好非阻塞代码?我会在我的getGroups 中传递回调吗? getGroups(account, callback)
    • 已经给出了细节
    【解决方案2】:

    由于account.getGroups 是一个异步函数,你自己的getGroups 也被强制为异步函数。不要使用return 语句返回名称,而是尝试将名称传递给回调:

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

    使用回调而不是返回语句编写的代码被称为连续传递风格。如果你想要更多的例子,你可以用谷歌搜索。

    如果您想传播错误,您可能还想将 seconf“错误”参数传递给回调以模仿 Nodejs 接口。

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多