0

i'm trying to preform a Firestore query to check if an email already exits in the database. I want to do this with a simple function and than check if the function returns with false or true, but the if statements gives an output before the function is even fired can somebody help me?

const admin     =   require("firebase-admin");

// Initialize Firebase connection
var serviceAccount = require("./fbAccount.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://ancobook-1aceb.firebaseio.com"
});

let db = admin.firestore();

function checkEmail(test) {
    let citiesRef = db.collection('users');
    let query = citiesRef.where('username', '=', test).get()
      .then(snapshot => {
        if (snapshot.empty) {
            console.log('No matching documents.');
          return true;
        }  

        snapshot.forEach(doc => {
            console.log('Matching documents');
          return false;
        });
      })
}

if (checkEmail('brancoschoenaker@gmail.com') == false) {
    console.log('Account already exists')
} else {
    console.log('Created Account')
}

Branco
  • 47
  • 7
  • Firestore queries and promise chains are all asynchronous and need to be treated as such. Your return statements are not returning from checkEmail, they are just returning from the callback functions, and those values are not being propagated upward. checkEmail should itself also return a promise that resolves with the value you want the caller to receive. – Doug Stevenson Jun 03 '20 at 19:23
  • And how do I do this, can you help me with that? – Branco Jun 03 '20 at 19:33
  • This is a very common thing - read the marked duplicate for discussion and examples. – Doug Stevenson Jun 03 '20 at 19:39
  • So I have read the discussion, and I know what to do I have to make the if statement wait until the function finished. but I can't figure out how to do it. – Branco Jun 03 '20 at 20:57
  • You can't. As I said, the function should return a promise that resolves with the data that the caller should get a holder. You might want to read up on how promises work. – Doug Stevenson Jun 03 '20 at 21:03
  • Solved it, thank you so much @DougStevenson – Branco Jun 05 '20 at 16:29

0 Answers0