user6039980 user6039980 - 6 months ago 42
Javascript Question

Firebase: Odd bug

I'm using the following code for creating users:

firebase.auth().createUserWithEmailAndPassword($scope.data.mail, $scope.data.pwd)
.catch(function(error)
{
});

var user;

while (!user)
{
user = firebase.auth().currentUser;
}


However I don't know why this time the user variable gets always a null value: and the loop never get finished. I'm currently unable to solve this issue.

Answer

You can't use a while loop to wait for an asynchronous result, because JavaScript runs on a single thread.

The loop will execute indefinitely, meaning the JavaScript runtime will never get a chance to handle the promise, even if it's completed.

You need to use the then clause of the promise instead.

firebase.auth().createUserWithEmailAndPassword($scope.data.mail, $scope.data.pwd)
  .then(function() {
     var user = firebase.auth().currentUser;
     // carry on executing code here
  })
  .catch(function(error) {
  });