【问题标题】:How to "control" when Firestore.getAll(...promises) stops by reject当 Firestore.getAll(...promises) 被拒绝时如何“控制”
【发布时间】:2020-01-17 10:14:31
【问题描述】:

上下文:

我正在做一个云功能来向多个用户发送推送。我需要恢复每个用户的信息以了解一些数据,例如姓名、国家/地区..等等。

问题:

实际上我恢复了用户 ID 列表,当我得到它时,我创建了一个 promises 数组来恢复所有信息:

var usersPromises = []
for (var i = 0; i < usersInRange.length; i++) {
   usersPromises[i] = firestore.collection("users").doc(usersInRange[i])
}

然后我恢复并使用firestore.getAll()发送推送:

firestore.getAll(...usersPromises).then(results => {
   for(snapshot in results){
      if(snapshot.exists){
         ......
         var user = snapshot.data()
         ......
      }else{
         ......
      }
   }
})

这个solution 实际上几乎一直在“正常”工作。但此时 Firestore db 有一些用户不存在或出现问题,因为方法 getAll()在完成所有承诺之前停止。我知道是因为没有发送push,并且在控制台中,只说方法已经完成。

阅读 SO 和文档,我看到,如果某些承诺被“破坏”,getAll 就会停止。 (全有或全无)

这就是我迷路的地方。我如何“强制”或以其他方式做,只是“跳跃”这个无法完成的承诺?

附注:

我尝试使用“for”,但它似乎省略了一些承诺:

for (var i = 0; i < usersPromises.length; i++) {
   usersPromises[i]
      .get()
      .then(snapshot => {
        if(snapshot.exists){
           ......
           var user = snapshot.data()
           ......
        }else{
           ......
        }
      })
}

【问题讨论】:

  • 你提到“有问题,因为getAll()方法在完成所有承诺之前停止”你能分享你整个Cloud Function的代码吗,因为它可能是由另一个问题引起(未返回的承诺)。顺便说一句,请注意您传递给getAll 的不是Promises,而是DocumentReferences 或ReadOptions

标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

我认为这不是getAll 的问题。我已经这样测试了:

const firestore = new Firestore();

let doc = []
doc[0] = firestore.doc('test/test');
doc[1] = firestore.doc('test/test1');
doc[2] = firestore.doc('test/doc');

firestore.getAll(...doc)
.then(result=> result.forEach(doc => console.log(doc._fieldsProto)))
.catch(err=>console.log(err));

在我的数据库中,我有“test/test”和“test/doc”文档,但没有“test/test1”,结果如下所示:

所以我们只在不存在的文档上获得undefined,仅此而已。建议加catch,看看有没有异常。当我一直在编写测试时,函数被内部函数中的拼写错误中断。

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多