Javascript 用承诺处理firestore任务

Javascript 用承诺处理firestore任务,javascript,html,collections,promise,google-cloud-firestore,Javascript,Html,Collections,Promise,Google Cloud Firestore,我对Firestore的承诺还不熟悉。我必须运行此任务: 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_u

我对Firestore的承诺还不熟悉。我必须运行此任务:

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);
          });  
这是第一个问题。这项任务完成后应该通知我。因此,只有当集合中的所有文档都被删除时。我试着用承诺来处理这件事。我不确定是否还有其他方法。提前谢谢

~filip

当所有
delete()
操作完成时,您可以使用返回一个
Promise
,您可以使用
then()
/
catch()
执行操作或处理错误。当返回
Promise
时,我们可以将每个删除操作推送到一个Promise数组中,我们可以使用
Promise.all()

另一个要考虑的选项是:

看起来批处理写入一次最多支持500个操作。请注意,您可以通过使用引用单个文档来简单地删除,而不是重新编写查询

希望这有帮助

当所有
delete()
操作完成时,您可以使用返回一个
Promise
,您可以使用
then()
/
catch()
执行操作或处理错误。当返回
Promise
时,我们可以将每个删除操作推送到一个Promise数组中,我们可以使用
Promise.all()

另一个要考虑的选项是:

看起来批处理写入一次最多支持500个操作。请注意,您可以通过使用引用单个文档来简单地删除,而不是重新编写查询


希望这有帮助

Array.prototype.map
.forEach
push
组合的替代品。@AZ_u。默认情况下,它不适用于数组,因为从技术上讲它不是数组,也没有
map()
之类的操作。哦,我不知道,谢谢。当你说“集合不退出”时,你是指外部get查询吗
get()
确实返回承诺。您的意思是在外部
then()
检查是否没有文档?也许您可以更新您的问题以反映您试图做什么以获得进一步的帮助?
Array.prototype.map
.forEach
push
组合的替代品。@AZ_z。默认情况下,这将无法使用,因为它在技术上不是一个数组,并且没有
map()之类的操作
在上面。哦,我不知道,谢谢。当你说“收集不退出”时,你是说外部get查询吗
get()
确实返回承诺。您的意思是在外部
then()
检查是否没有文档?也许您可以更新您的问题,以反映您正试图做些什么以获得进一步的帮助?
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));
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!'));