1

I have a function:

var Ref = db.collection('Test').doc('Document');

function fire() {
    var getDoc = Ref.get()
     .then(doc => {
         if(doc.exists){
            return doc.data().Num
         }else{
             return
         }

     })
     .catch(err => {
        console.log('Error getting document', err);
    });
}

console.log(fire()); // undefined

How could I get this working so it returns the document from firestore? I need a function for what I am trying to do, I'm aware that you can do this regularly without one.

Landon G
  • 819
  • 2
  • 12
  • 31
  • Use `promises`, `async/await`. These are asynchronous calls. – Shubham May 28 '19 at 05:23
  • @Shubham I've tried using async/await and I can't access them at global scope. Would you mind posting a code sample? (I might be doing something wrong) – Landon G May 28 '19 at 05:26
  • Your `fire` function is `asynchronous` and your console.log is running synchronously. Use `async/await`. – random May 28 '19 at 05:27
  • @randomSoul would you mind posting a code sample? I'm very inexperienced with async and node as whole – Landon G May 28 '19 at 05:28
  • `(async () => { function fire() { var doc = await Ref.get(); if(doc.exists) { return doc.data().Num;} return null;}})();`. Put the code in `try...catch` block to trap any errors if encountered. – random May 28 '19 at 05:32
  • Overall I'm not having any luck with async – Landon G May 28 '19 at 05:46
  • @LandonG - What error do you get? See - http://collabedit.com/eut6f. – random May 28 '19 at 05:54
  • `var getDoc = await Ref.get(); SyntaxError: await is only valid in async function`, also `err` part has a red underline which will throw an error – Landon G May 28 '19 at 06:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/194031/discussion-between-randomsoul-and-landon-g). – random May 28 '19 at 06:15

0 Answers0