0

I get the image URLs from firebase storage then I push every URL into a separate array to use it later when I setState,

but when I log the imgUrls outside ForEach it returns empty array!

And I tried to use Promise.all() but not work and i can't set the state!

So what the wrong i made?

getImages = async () => {
    const refList = storage().ref('/categories/Air/');
    const listAll = await refList.listAll();
    let imgUrls = [];

    let promise = listAll.items.forEach(async itemRef => {
      try {
        let url = await itemRef.getDownloadURL();
        imgUrls.push(url);
        console.log('array-imgUrls', imgUrls);
      } catch (error) {
        console.log('error', error); 
      }
    });

   const imageUrls = await Promise.all(promise).then(()=>{
      this.setState({URLs:imgUrls})
    });
    console.log("imageUrls",imageUrls);
}
Oliver D
  • 2,579
  • 6
  • 37
  • 80
  • forEach doesn't return a promise, and async/await isn't working the way you expect inside the loop. You will need to collect the downloadURL promises into an array and await them with Promise.all (or one of the many other options you have, discussed throughout Stack Overflow). – Doug Stevenson Apr 13 '20 at 00:00
  • @DougStevenson yes that's right, i just see it in this [blog](https://zellwk.com/blog/async-await-in-loops/) "if anyone interested" so I use map() instead of forEach and it works, Thanks – Oliver D Apr 13 '20 at 00:20

0 Answers0