-1

I am trying to populate a constant variable with a foreach loop, which it does correctly inside the loop, but it doesn't keep its value when it gets out of the loop. Does anyone know why this is happening?

I am fetching data from a firestorm database which I am then trying to save in a constant object `

const customers = {};

customersRef.get()
.then((snapshot) => {
    snapshot.docs.forEach((doc) => {
        customers[doc.id] = doc.data();
    });
    console.log(customers);
}).catch((e) => {
    console.log(e.message);
});

console.log(customers);

`

This gives me the output: `

{
    "correctId": {
        "some": "secretData"
    },
    "correctId": {
        "some": "secretData"
    }
}

{}

`

The console.log()within the loop gives me the correct data while the same console.log() beneath gives me an empty object

  • 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) – Konrad Nov 14 '22 at 12:15
  • I'm afraid I couldn't find what I was looking for there – Anton Norman Nov 14 '22 at 12:33

1 Answers1

-1

You are not storing the result anywhere. Yo are missing customers = customersRef.get() ... at the beginning of your statement.

const customers = {};

customers = customersRef.get()
.then((snapshot) => {
    snapshot.docs.forEach((doc) => {
        customers[doc.id] = doc.data();
    });
    console.log(customers);
}).catch((e) => {
    console.log(e.message);
});

console.log(customers);
pe.kne
  • 655
  • 3
  • 16