Q:

Handling firestore tasks with Promises

I am new to Promises for Firestore. I have to run this task:  
db.collection("users").doc(user_uid).collection("grades").doc("g").collection("es111").get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
              db.collection("users").doc(user_uid).collection("grades").doc("g").collection("es111").doc(doc.id).delete();
            });
          })
          .catch(function(error) {
            console.log("Error getting documents: ", error);
          });  

Here is the first Problem. This task should notice me when its finished. So only if al documents in the collection are deleted. I try to handle this with a promise. I am not sure maybe there are other ways. Thanks in advance.
~filip

A:

You may be able to use Promise.all to return a Promise when all delete() actions have completed that you can use with then()/catch() to perform an action or handle errors. As delete returns Promise<void> we can push each delete action to an array of promises that we can use with Promise.all():
function foo(user_uid) {
  return db.collection("users").doc(user_uid).collection("grades").doc("g").collection("es111").get().then(function(querySnapshot) {
    let promises = [];

    querySnapshot.forEach(function(doc) {
      // add each delete() promise to promises array
      promises.push(db.collection("users").doc(user_uid).collection("grades").doc("g").collection("es111").doc(doc.id).delete());
      // or more simply
      // promises.push(doc.ref.delete());
    });

    return Promise.all(promises);
  })
  .catch(function(error) {
    console.log("Error getting documents: ", error);
  });
}

// ...

// usage
foo()
  .then(() => console.log('Success!'))
  .catch(err => console.error(err));

Another option to consider is using batched writes:
db.collection("users").doc(user_uid).collection("grades").doc("g").collection("es111").get().then(function(querySnapshot) {
    const batch = db.batch();

    querySnapshot.forEach(function(doc) {
      batch.delete(doc.ref);
    });

    return batch.commit();
  })
  .then(() => console.log('Batched delete completed!'));

It looks like batched writes support a maximum of 500 operations at at time. Notice that you can simply the delete by using DocumentSnapshot.ref to reference the individual document instead of re-writing the query.
Hopefully that helps!

