【发布时间】:2019-03-25 10:45:02
【问题描述】:
我有一个这样的 Firebase 数据库(例如):
{
'itemCategories': [
_categoryKey1: {
name: 'Category 1'
},
_categoryKey2: {
name: 'Category 2'
},
_categoryKey3: {
name: 'Category 3'
},
],
'items': [
_itemKey1: {
categoryId: '_categoryKey1',
name: 'Item 1',
}
_itemKey2: {
categoryId: '_categoryKey2',
name: 'Item 2',
}
_itemKey3: {
categoryId: '_categoryKey1',
name: 'Item 3',
}
_itemKey4: {
categoryId: '_categoryKey3',
name: 'Item 4',
}
_itemKey5: {
categoryId: '_categoryKey3',
name: 'Item 5',
}
]
}
我想要得到的是按类别分组的一组项目,例如:
itemList = [
{
category: 'Category 1',
items: [
{
id: '_itemKey1',
categoryId: '_categoryKey1',
name: 'Item 1',
},
{
id: '_itemKey3',
categoryId: '_categoryKey1',
name: 'Item 3',
}
]
},
{
category: 'Category 2',
items: [
{
id: '_itemKey2',
categoryId: '_categoryKey2',
name: 'Item 2',
}
]
},
{
category: 'Category 3',
items: [
{
id: '_itemKey4',
categoryId: '_categoryKey3',
name: 'Item 4',
},
{
id: '_itemKey5',
categoryId: '_categoryKey3',
name: 'Item 5',
},
]
},
]
我使用react-redux 操作来实现这一点,如下所示:
export const setItemList = (list) => {
return {
type: 'setItemList',
value: list
}
}
export const getItemListByCategory = () => {
return (dispatch) => {
let itemList = []
firebase.database().ref('itemCategories').on('value', (snapCategory) => {
snapCategory.forEach((category) => {
const categoryId = category.key
firebase.database().ref('items').orderByChild('categoryId').equalTo(categoryId).on('value', (snapItem) => {
let items = []
snapItem.forEach((item) => {
items.push({
id: item.key,
...item.val()
})
})
itemList.push({
category: category.val().name,
items: items
})
// This is where I think is the issue
dispatch(setItemList(itemList))
})
})
// The dispatch should be there, when every calls resolved
})
}
}
这很好用,大部分情况下。
由于我处于forEach 循环中,我将按类别检索数据,并实际调度多个 partial itemList 直到forEach 循环结束。
显然,我宁愿等到循环结束然后发送完整的itemList。
我不知道如何等待循环结束 - 以及所有要解决的调用。
我觉得我应该使用Promise,但我不确定如何实现它。
【问题讨论】:
标签: firebase react-native firebase-realtime-database promise react-native-firebase