-1

I have a method in a class that returns a Firebase user document:

class FirebaseUtils {
  async getUserDocument(uid) {
    if (!uid) return null
    try {
      const userDocument = await this.firestore.collection('users').doc(uid).get()
      return { uid, ...userDocument.data() }
    } catch (error) {
      console.error('error getting user document: ', error)
    }
  }
}

I am getting Promise {<pending>} when I try to get the result of this function in another file

//need to update userDocument later
const userDocument = firebaseUtils.getUserDocument(uid)
console.log(userDocument) //Promise {<pending>}

I've tried this as well ascreating an immediatelly invoked function to await the getUserDocument function but that didn't work.

uber
  • 4,163
  • 5
  • 26
  • 55
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Emile Bergeron May 21 '20 at 14:47
  • unfortunately not, I'd come accross that before but my terminal screams ```Parsing error: Can not use keyword 'await' outside an async function``` at me (and I tried exactly as the proposed answer by cbr below) – uber May 21 '20 at 14:59
  • `async/await` is only one of the ways to manage asynchronous flow in JS. You can use `then` anywhere there's a promise involved. – Emile Bergeron May 21 '20 at 15:16

1 Answers1

1

Since async functions return a Promise, you'll need to await or use .then to get the resolved value:

const userDocument = await firebaseUtils.getUserDocument(uid)
console.log(userDocument)

or

firebaseUtils.getUserDocument(uid).then((userDocument) => {
  console.log(userDocument)
})

As a side note, you'll probably want to return null after logging the error in the catch, or at least be aware of the fact that the function returns undefined in that case.

cbr
  • 12,563
  • 3
  • 38
  • 63
  • When I try to await it, I get ```Parsing error: Can not use keyword 'await' outside an async function``` – uber May 21 '20 at 14:54
  • 1
    That is correct when you use the first snippet. So the function that contains this `await firebaseUtils.getUserDocument(uid)` will also need to be marked as `async`. Alternatively, you can use `then()` as shown in the second snippet. – Frank van Puffelen May 21 '20 at 15:01
  • 1
    This is because you are trying to use await outside an async function. You can only use `await` inside a function that is marked `async` unless you are using babel plugins to use top-level-await. If you don't want to create another async function then you can always use `.then` to resolve the promise. – subashMahapatra May 21 '20 at 15:08