angularjs - Javascript Method always returns false -


this question has answer here:

i'm attempting check user before saving them in firebase users table, when go check using .once() firebase method, function returns false...

when console.log inside function, logs correctly, never returns true.

auth represents basic firebase auth factory

var newuser = function(id) {   ref.child('users').child(id).once('value', function(snapshot) {     console.log(snapshot.val() === null);     return (snapshot.val() === null);   }); };  auth.$onauth(function(authdata) {   console.log(boolean(newuser(authdata.uid)));   if (authdata && !!(newuser(authdata.uid))) { // add user if first time login     $scope.authdata = authdata;     ref.child('users').child(authdata.uid).$save({       provider: authdata.uid,       name: getname(authdata),       blah: 'blah'     });     $state.go('main.home');   } else if (authdata) {     $state.go('main.home');   } else {     console.log('not logged in');   } }); 

your new user function doesn't return anything. maybe see if move callback function out it's own named function.

var onvalue = function(snapshot) {   console.log(snapshot.val() === null);   return (snapshot.val() === null);     };  var newuser = function(id) {   ref.child('users').child(id).once('value', onvalue);   // new user doesn't return }; 

when omit return value, function automatically return undefined, coercing boolean — resulting in false.

the problem here callback firebase's .once method runs after function (fails to) return value. because asynchronous.

this common problem new javascript developers, can visualized small example.

function doasync() {   settimeout(function() {     console.log('a');     return 'a';   }, 3000);    console.log('b');   return 'b'; } doasync(); 

what order expect console.log statements run? value expect function return? if it's not obvious, spend time experimenting code in console.

obviously, it's still important able values out of async functions. 1 way callback functions.

in case, add callback parameter new user function, call function new user available.

var newuser = function(id, done) {   ref.child('users').child(id).once('value', function(snapshot) {     done(snapshot.val() === null);   }); }; 

then amend other code work style.

auth.$onauth(function(authdata) {   newuser(authdata.uid, function(val) {     // result   }); }); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -