2

Not quite sure how to return result to outer function, i want to call getListOfUsers() and get returned list of results

function getListOfUsers() {
    userlist.getUsers(function(next, res) {
       var result = JSON.parse(res);
       var listOfUsers = result.members.map(function (mem) {
            return mem.name;
        });
    });
}

If i return outside of the map, it will obviously return undefined, or null if i define it outside and initiate it inside. Using promises leaves me in same situation where my return is inside the 'then' function. Whats common practice here?

John O'Donnell
  • 159
  • 2
  • 11
  • 1
    possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Mar 26 '15 at 01:06

1 Answers1

0

Seemingly, userlist.getUsers is an asynchronous function which means that you have to treat it asynchronously and use callbacks (via promises, continuations, or whichever style you prefer) to pass the retrieved data to other code.

function getListOfUsers(cb) {
    userlist.getUsers(function(next, res) {
       var result = JSON.parse(res);
       var listOfUsers = result.members.map(function (mem) {
           return mem.name;
       });
       cb(null, listOfUsers);
    });
}

Then instead of doing this:

var users = getListOfUsers();
// do things with users

You would do this:

getListOfUsers(function (err, users) {
    // do things with users
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • thanks, the reason i wanted to do something like var users = getListOfUsers(); was because i wanted to trigger that function only once i.e make a request, store results in variable and then dont make request again if variable has results; – John O'Donnell Mar 26 '15 at 00:03
  • @JohnO'Donnell you can certainly do that, it's just that all of the code that depends on the initial value of users has to be done within the context of the callback. – Explosion Pills Mar 26 '15 at 00:06