0

im trying to get the data of a single document and save it to a variable for use it later in another logic operation. The firestore documentation show hot to do this only with promises but i can't set the doc.data() value to a variable for later use, only inside the then() or catch() method. I can set a variable there but i can't use it outside the promise.

Firestore documentation example:

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user3785328
  • 674
  • 7
  • 6
  • If the variable is declared outside, you can very well set it from within the `then` function. –  Nov 27 '17 at 23:11
  • 2
    Don't fight against asynchronism, you won't ever win. Learn how asynchronous code works, how to use it. What you're basically asking for is how to get a synchronous result from an asynchronous function - it can not be done, ever. Perhaps the `async/await` "sugar" will help you. While it's still asynchronous, it looks less daunting for some people – Jaromanda X Nov 27 '17 at 23:27

1 Answers1

3

As Jaromanda X commented: you're best of accepting the asynchronous nature of Firebase and most of the modern web. The sooner you get to grips with the programming patterns, the sooner you can get back to being productive in this paradigm.

I find it most helpful to reframe problems. Instead of "Load a document, then do something with it" I frame it as "First start loading a document. Once the document has loaded, do something with it".

In practice that means that you move your code that needs the document into the completion handler where you now have the logging statements.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807