javascript - Why is my function not returning the array? -


this question has answer here:

this 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 debugger in see problem not help. when go console , type in users_array uncaught referenceerror: users_array not defined(…)

new code (edit):

according stackoverflow answers 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   }); } 

the return value users_array local scope of anonymous callback function function(snapshot) {.... in other words, value lost outside of scope.

at point in logic need access user_array? if need access outside of context of functions, maybe makes sense define variable greater scope, , setting value in anonymous function. e.g.

document.getelementbyid... var arr;  ...  function pullallusersfromdb() {     ...     ...function(snapshot) {         arr = users_array;     }); }  // pullallusersfromdb() (and callback) must called arr defined @ point in execution 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -