【问题标题】:Unhandled error TypeError: snapshot.val is not a function when using forEach Firebase Cloud Functions未处理的错误 TypeError: snapshot.val is not a function when using forEach Firebase Cloud Functions
【发布时间】:2018-06-20 15:24:14
【问题描述】:

我正在编写一个带有 HTTPS 触发器的 Firebase 云函数,并且我正在使用 Promise.all(arrayOfPromises) 一次启动多个读取操作,当所有承诺都得到满足时,then(snapshotContainsArrayOfSnapshots) 方法被触发,我尝试用forEach(snapshot) 方法迭代snapshotContainsArrayOfSnapshots,但我得到了这个错误:

Unhandled error TypeError: snapshot.val is not a function

代码如下: f

let promisesArray = []
for(let i = 0; i < 10; i++){
    const promise = db.ref(`/questions/en/${i}`)
    promisesArray.push(promise)
}
return Promise.all(promisesArray)
    .then((snapshotContainsArrayOfSnapshots) => {
        let data = []
        snapshotContainsArrayOfSnapshots.forEach((snapshot) => {
            data.push(snapshot.val())
        })
        return JSON.stringify(data)
    })

记住:这不是onWrite 触发器,所以我不需要调用change.after

【问题讨论】:

  • 您能否添加其余代码,特别是您在promisesArray中的承诺类型
  • @RenaudTarnec 我已经编辑了这个问题。

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


【解决方案1】:

您添加到promisesArray 的是References,请参阅文档here

对于您的每一个引用,您应该使用once() 方法(doc here)查询引用处的数据,并且您需要将此方法返回的承诺添加到您的promisesArray

那么做如下:

let promisesArray = []
for(let i = 0; i < 10; i++){
    const promise = db.ref(`/questions/en/${i}`).once('value');
    promisesArray.push(promise)
}
return Promise.all(promisesArray)
    .then((snapshotContainsArrayOfSnapshots) => {
        let data = []
        snapshotContainsArrayOfSnapshots.forEach((snapshot) => {
            data.push(snapshot.val())
        })
        return JSON.stringify(data)
    })

【讨论】:

  • 谢谢,它成功了,但我收到了这个警告:[2018-06-20T15:44:20.943Z] @firebase/database: FIREBASE WARNING: Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "full" at /multiplayer_games to your security rules for better performance.
猜你喜欢
  • 2021-04-22
  • 2013-10-20
  • 1970-01-01
  • 2016-04-02
  • 2016-09-14
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多