【发布时间】: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