Home > Enterprise >  Firebase snapshot.forEach(async () => {}) not working properly
Firebase snapshot.forEach(async () => {}) not working properly

Time:11-11

I have a code here, that loads posts from firebase collection "posts" But it does not work the way I expect. There are two documents in collection "posts" But the result of console.log() is this. It initially has 0 items, and only after it is populated with two documents. I think that the problem is in this line:

const photoUrl = await getDownloadURL(ref(storage, data.photoPath))

Because when I remove it, it works fine(array is populated before it is logged in the console, like this). Please help!

CodePudding user response:

Probably you need to consider reconstruct your code a little bit. The problem is that the code ends before the asynchronous operations finish. Even though you added await when you are trying to download, but the entire operation in the foreach bracket async (doc) => {....} is still an asynchronous operation.

What you can do is to reorganize your code into this way:

const promiseList = []

snapShot.forEach(doc => promiseList.push(asyncFunctionToCompleteYourData(doc)))

await Promise.all(promiseList)

Besides, you probably needs to check your lint rules, because usually for JavaScript it should directly throw an error if you are directly writing async code in a for loop.

  • Related