简体   繁体   中英

Unhandled error TypeError: snapshot.val is not a function when using forEach Firebase Cloud Functions

I'm writing a Firebase Cloud Function, with an HTTPS trigger, and I am starting more that one read operation at once using Promise.all(arrayOfPromises) , when all of the promises are fulfilled the then(snapshotContainsArrayOfSnapshots) method gets triggered, and I try to iterate the snapshotContainsArrayOfSnapshots with forEach(snapshot) method, but I get this Error:

Unhandled error TypeError: snapshot.val is not a function

Here is the code: 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)
    })

Remember: This ISN'T an onWrite trigger so I dont need to call change.after .

What you are adding to the promisesArray are References , see doc here

For each of your references, you should query the data at the reference with the once() method (doc here ) and it is the promise returned by this method that you need to add to your promisesArray .

So do as follows:

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)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM