簡體   English   中英

循環收集Firebase Cloud函數異步調用的結果

[英]Collect results from firebase cloud function async call in a loop

我試圖在循環中查詢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(),而是可以只對令牌進行一次數組調用並將其完成。

道格做出回應后,請認真考慮一下我對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])
        })
    })
}

該調用是異步的,並立即返回:

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

而且,在返回數組otherUserNotificationids之前,您不必等待它完成。

另外,似乎您對將什么傳遞給Promise.all()誤解了。 Promise.all()接受一系列的promise,在解決它返回的promise之前要等待,這不是您要做的。

相反,應該做的是將對once() Promise.all()的重復調用返回的所有promise收集到一個數組中,將該數組傳遞給Promise.all() ,然后在其返回的promise解析后,處理回調中可用的所有快照。 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM