0

With the following async function I get data from a firebase firestore instance:

export async function getSomething(db, id) {
  db.collection('someting').doc(id).get().then((doc) => {
    if (doc.exists) {
      return doc.data();
    }
    throw new Error('No such document!');
  }).catch((error) => {
    throw new Error('err', error);
  });
}

I called this function like:

getSomething(db, this.id).then((data) => {
  console.log(data); // data is empty here
}).catch((err) => {
  console.log(err);
});

The issue is, that on the data from the then function is empty. How can I get the data from the getSomething function? Is returning the data not enough?

Zoker
  • 1,850
  • 4
  • 24
  • 43
  • 2
    1) There's no reason for your function to be `async` since you're not using `await`. 2) `return db.collection...` – Phil Dec 16 '18 at 22:42
  • 2
    Why are you using an async function will there is no use of `await` operator? – chriptus13 Dec 16 '18 at 22:43
  • Possible duplicate of [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) – Phil Dec 16 '18 at 22:57

1 Answers1

3

If you want to get a value back from a function, then you need to return something from it.

You have a number of return statements, but they are all inside callbacks.

You need one for getSomething itself.

return db.collection('someting').doc(id).get().then((doc) => {
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205