how to check a loop when finished adding data to firestore

I have a list of fruit lists

 Object.keys(fruit).forEach(function (item) {
                   
                        firebase.firestore().collection("FruitBasket").doc().set({
                            name:item.name,
                            width:item.width,
                            height:item.height
                        }).then(() => {
                                //complete add one fruit
                        })
                      }
                 })

how can i check when the whole Fruit Basket is added?

Upvotes: 0

Views: 74

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

Since you don't know upfront the number of asynchronous calls that you want to run in parallel, you should use Promise.all() as follows:

  const promises = [];

  Object.keys(fruit).forEach((item) => {          
    promises.push(
    firebase
      .firestore()
      .collection('FruitBasket')
      .add({
        name: item.name,
        width: item.width,
        height: item.height,
      }));
  });

  Promise.all(promises)  // Returns a single Promise
  .then(() => {
    //  Here the whole Fruit Basket is added
  })

PS1: Note that instead of doc().set(...) you can do add(...).


PS2: Note the possibility to use a batched write. Potential drawback: it has a limit of 500 docs, which Promise.all() doesn't have.

Upvotes: 3

Related Questions