1
function isDisplayNameTaken(name) {
  firebase
    .database()
    .ref()
    .child("users")
    .orderByChild("username")
    .equalTo(name)
    .once("value")
    .then((snapshot) => {
      return snapshot.exists();
    });
}

I've been trying to check if a username is already in the database before registering a user, but the return does not work, nor does anything inside function(snapshot) change other global variables to go around it.

if(isDisplayNameTaken($userDisplayNameField.val())) {
  numberOfChecksPassed += 1
}

This is the condition that does not pass through. I've done my research and been trying to solve the problem for the last 5 hours. Thanks in advance

Jim Wright
  • 5,905
  • 1
  • 15
  • 34

1 Answers1

1

First off, you can't use promise results as you are trying to in a simple if statement. You should do the following:

isDisplayNameTaken($userdisplayNameField.val()).then(taken => {
    console.log('Is it taken?', taken);
});

In your example with a simple if - the if statement is checking the promise object as its conditional rather than the resolved value.

For this to work, isDisplayNameTaken will need to return a promise (which it doesn't).

function isDisplayNameTaken(name) {
  return firebase // Notice the return here.
    .database()
    .ref()
    .child("users")
    .orderByChild("username")
    .equalTo(name)
    .once("value")
    .then((snapshot) => {
      return snapshot.exists(); // This return will resolve the promise but you are not returning the resolved promise out of the function.
    });
}
Jim Wright
  • 5,905
  • 1
  • 15
  • 34