2

i am trying to fetch all images in firebase storage. So far it works. But the problem is how to put ALL data inside array in asynchronous function and not just one then pass it into state?

My Code :

   async componentDidMount(){
        auth().signInAnonymously();

        var arr = [];
        var storageRef = storage().ref("/madu_mubarak/");
        await storageRef.listAll().then((result)=> {
            result.items.forEach((imageItem) =>{
              this.displayItem(imageItem)
            });
          }).catch(function(error) {
            console.warn("error "+error);
          });


    }

    async displayItem(imageItem){
        var arr = [];
        imageItem.getDownloadURL().
            then((url) => {
          console.warn("ur "+url)
          arr.push(url);
          this.setState({
            isLoad: false,
            urlImage: arr
          })
        }).catch((error) =>{
          console.warn("error "+error);
        });


        // return await Promise.all(arr);
    }

Please help. Thank you

2
  • Take a look at Promise.all([...]). You can pass it an array of promises and it resolves only when all promises in the array resolves Commented Apr 28, 2020 at 6:13
  • @TomSlutsky i already look at Promise.all. But i am still new at that so i dont understand how to implement. Commented Apr 28, 2020 at 7:00

1 Answer 1

2

The main gist is this


async componentDidMount(){
        auth().signInAnonymously();


        var storageRef = storage().ref("/madu_mubarak/");
        await storageRef.listAll().then((result)=> {
           let promises = result.items.map((imageItem) =>{
              return imageItem.getDownloadURL()
            });
            Promise.all(promises).then(urls => this.setState({images: urls})

    }

You want to create an array of the promises returned from getDownloadUrl and the wait for all of them to resolve with Primise.all you can then assign the result to the state

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.