【问题标题】:Collect results from firebase cloud function async call in a loop从循环中收集firebase云函数异步调用的结果
【发布时间】:2018-03-17 07:46:11
【问题描述】:

我试图循环查询firebase数据,然后我需要从那里收集数据创建一个数据集合并返回到调用函数。

以下是我的代码,我无法收集结果,并且在所有结果都收集到数组中之前执行 return 语句。

function xyz() {
    ...
    // variable lookupKey is defined above this function
    return dbRef.child(`/location/${lookupKey}`).once('value').then(contacts => {
        const otherUserNotificationids = []
        contacts.forEach(function(element) {
            var id = element.val()
            console.log(`found id: ${id}`)
            dbRef.child(`/tokenLookup/${id}`).once('value').then(notifId => {
                const nVal = notifId.val()
                console.log(`found notification id : ${nVal}`)
                otherUserNotificationids.push(nVal)
            })
        });
        const len = otherUserNotificationids.length
        console.log(`found notificationIds count : ${len}`)
        return Promise.all([otherUserNotificationids])
    })
}

正如预期的那样,函数以 'found notificationIds count : 0' 结束,

如何收集调用 /tokenLookup/${id} 的结果并从中创建一个集合。

我正在这样做,因此我不必为每个令牌调用 admin.messasing().sendToDevice(),而是可以使用令牌数组调用一次并完成。

在 Doug 的回复之后,我认真考虑了我对 Promises 的使用,这就是我解决它的方法:

function xyz() {
   //moved this variable to top of function (rather then inner scope)
   const otherUserNotificationids = []    
    ...
    // variable lookupKey is defined above this function
    return dbRef.child(`/location/${lookupKey}`).once('value').then(contacts => {
        const promises = []
        contacts.forEach(function(element) {
            var id = element.val()
            console.log(`found id: ${id}`)
            const prms = dbRef.child(`/tokenLookup/${id}`).once('value').then(notifId => {
                const nVal = notifId.val()
                console.log(`found notification id : ${nVal}`)
                otherUserNotificationids.push(nVal)
            })
            promises.push(prms)
        });
        return Promise.all(promises).then(res => {
        const len = otherUserNotificationids.length
        console.log(`found notificationIds count : ${len}`)
        return Promise.all([otherUserNotificationids])
        })
    })
}

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    此调用是异步的,并立即返回:

    dbRef.child(`/tokenLookup/${id}`).once('value').then(...)
    

    而且在返回数组 otherUserNotificationids 之前,您无需等待它完成。

    此外,您似乎对传递给Promise.all() 的内容产生了误解。 Promise.all() 接受一系列要等待的承诺,然后再解决它返回的承诺,这不是你正在做的。

    应该做的是将重复调用once()返回的所有promise收集到一个数组中,将数组传递给Promise.all(),然后在它返回的promise解析后,处理所有可用的快照回调。

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2019-06-02
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多