-1

This is my code:

document.getElementById('revealUser').onclick = displayDaUsers

function displayDaUsers(){
  pullAllUsersFromDB();
  debugger;
}


function pullAllUsersFromDB(){
  rootRef.child('users').on('value', function(snapshot) {
    var users_array = [];
    var users_object = snapshot.val();
    Object.keys(users_object).map(function(key) {
      users_array.push(users_object[key]);
    });
    // window.dateApp.allUsers = users_array;
    return users_array
  });
}

html:

<input type="submit" id="revealUser" value="reveal user">

I put a debugger in to see the problem but it does not help. When I go into the console and type in users_array I get Uncaught ReferenceError: users_array is not defined(…)

NEW CODE (EDIT):

according to another stackoverflow answers this should work..

function displayDaUsers(){
  var test = pullAllUsersFromDB();
  console.log(test);
  //pullAllUsersFromDB();
  //debugger;
  //setUpFirstUser()
}


function pullAllUsersFromDB(){
  rootRef.child('users').on('value', function(snapshot) {
    var users_array = [];
    var users_object = snapshot.val();
    Object.keys(users_object).map(function(key) {
      users_array.push(users_object[key]);
    });
    //window.dateApp.allUsers = users_array;
    return users_array
  });
}
Waterman1
  • 135
  • 1
  • 3
  • 11

1 Answers1

0

The return value users_array is local to the scope of the anonymous callback function function(snapshot) {.... In other words, its value is lost outside of that scope.

At what point in your logic do you need access to user_array? If you need access to it outside of the context of your functions, maybe it makes sense to define a variable with greater scope, and then setting its value in your anonymous function. E.g.

document.getElementById...
var arr;

...

function pullAllUsersFromDB() {
    ...
    ...function(snapshot) {
        arr = users_array;
    });
}

// pullAllUsersFromDB() (and its callback) must be called for arr to be defined at this point in execution
  • I need it to be accessible to the other method `displayDaUsers`. is that not possible? – Waterman1 Sep 12 '16 at 18:46
  • If that is the case then it makes sense to pass in `users_array` as a callback value that `displayDaUsers` can access. So, `pullAllUsersFromDB` should be augmented with a callback parameter. –  Sep 12 '16 at 18:48
  • so how would that look? what argument would `pullAllUsersFromDB` take and what would it look like inside the other function? (i'm not asking you to do it for me, just need to learn how this type of scoping works) – Waterman1 Sep 12 '16 at 18:52
  • edited now dude – Waterman1 Sep 12 '16 at 19:21
  • Please see the answers to the duplicate question: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –  Sep 12 '16 at 20:17