1

Need a second pair of eyes... spot anything wrong with this? My inner function is not returning the value. I must be messing something up with the scope?

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

When assigning the variable in the parent function ie var name = 'assigned' it works.

user3311351
  • 301
  • 1
  • 2
  • 9

2 Answers2

2

You account.getGroups might be an asynchronous function and it takes a callback function. this callback function,

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

does not get executed instantaneously. So your return name; statements gets executed before your name = 'test'; statement.

Hope it makes sense.


to get the updated value from the callback you have to make the getGroups asynchronous or event based

making asynchronous is easy

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

}

and instead of calling the function for value (e.g., 'var groupname = getGroups(account)') you have to do like the following

getGroup(account, function (groupname){
   // do whatever you like with the groupname here inside this function
})
Kamrul
  • 7,175
  • 3
  • 31
  • 31
  • 1
    It does. However how can I structure this to maintain good non blocking code with the needed returned results? Would I pass a callback within my `getGroups`? `getGroups(account, callback)` – user3311351 Jul 01 '14 at 00:38
  • have given the detail – Kamrul Jul 01 '14 at 00:48
1

Since account.getGroups is an async function, your own getGroups is also forced to be async. Instead of returning the name with a return statement, try passing the name to a callback once you have it:

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

Code written with callbacks instead of return statements is said to be written in continuation passing style. You can google for that if you want more examples.

You might also want to pass a seconf "error" parameter to the callback to mimic the Nodejs interface if you want to propagate errors.

hugomg
  • 68,213
  • 24
  • 160
  • 246