-1

I have a promise and the console.log inside of the promise gives me a string, but I cant use the result outside of the promise as the result is undefined.

   const docId = firebase
    .firestore()
    .collection('users')
    .doc(user.uid)
    .collection('payments')
    .get()
    .then(querySnapshot => {
        querySnapshot.forEach(doc => {
            console.log(doc.id);
            return doc.id;
        });
    });

console.log(docId);

So console.log(doc.id) return a value, but I can't get the result and use it outside of the const docId. Is there a way to grab the result of doc.id and use it outside of the const docId?

zhulien
  • 5,145
  • 3
  • 22
  • 36
Hesam Alavi
  • 149
  • 3
  • 12
  • 4
    promises are asynchronous - you're console.log runs before the firestore stuff even starts – Bravo Jul 27 '21 at 09:10
  • 4
    @Bravo furthermore, the final `then` doesn't have a return value, so the promise chain will produce `undefined` in the end anyway. – VLAZ Jul 27 '21 at 09:11
  • 1
    Bravo and VLAZ are correct. You can learn how to use promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – CunningFatalist Jul 27 '21 at 09:12
  • 1
    you should return data from `.then` statement, something like: `return querySnapshot.map(doc => doc.id)`, in such case docId will be an array of ids – Oleksandr Sakun Jul 27 '21 at 09:12
  • 1
    Also `forEach` returns nothing.. – Keith Jul 27 '21 at 09:13
  • Also [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) – Ivar Jul 27 '21 at 09:17

1 Answers1

3

You're never returning a value in the final .then statement. One way to use the value outside the promise is to use a variable defined outside the promise, or you could use await as so:

// If you're in an async function you can use await to get the result of the promise
const docId = await firebase
    .firestore()
    .collection('users')
    .doc(user.uid)
    .collection('payments')
    .get()
    .then(querySnapshot => {
        querySnapshot.forEach(doc => {
            console.log(doc.id);
            return doc.id; // The return here does nothing
        });
        // You need to return something here
        return querySnapshot[0].id;
    });

console.log(docId);
JonasMH
  • 1,145
  • 11
  • 21