请告诉我,如何将数据放入队列返回数组中。因为组件渲染速度比firebase快,所以发送数据。
来自行动的代码片段(redux' s)
function fetchPosts(key) {
return dispatch => {
dispatch(requestPosts(key))
return database.ref('article/').once('value', snap => {
let childData = []
snap.forEach(function(child) {
getImage(child.val().thumb).then((url) => {
console.log(url)
return {
"id": child.key,
"url": url,
...child.val()
}
}).then((array) => {
console.log(array)
childData.push(array)
})
})
dispatch(receivePosts(key, childData))
})
.catch((error) => {
console.log(error)
dispatch(receivePosts(error))
})
}
}
答案 0 :(得分:0)
您需要等待所有快照响应,例如:
// Boilerplate start ---
function getImage(thumb) {
return new Promise((resolve) => {
setTimeout(() => resolve(thumb + ' url'), Math.random() * 500);
});
}
function Child(key, value) {
this.key = key;
this.value = value;
}
Child.prototype.val = function () {
return this.value;
}
function receivePosts(key, childData) {
return {key, childData};
}
function dispatch(action) {
console.log(action);
}
snap = [
new Child('key1', {thumb: 'thumb1'}),
new Child('key2', {thumb: 'thumb2'}),
new Child('key3', {thumb: 'thumb3'}),
new Child('key4', {thumb: 'thumb4'}),
new Child('key5', {thumb: 'thumb5'}),
new Child('key6', {thumb: 'thumb6'}),
new Child('key7', {thumb: 'thumb7'}),
new Child('key8', {thumb: 'thumb8'})
];
// Boilerplate end ---
function insideDatabaseRefOnce(key) {
return Promise.all(snap.map(function(child) {
return getImage(child.val().thumb).then((url) => {
return {
"id": child.key,
"url": url,
...child.val()
}
});
})).then((childData) => {
dispatch(receivePosts(key, childData))
});
}
insideDatabaseRefOnce('The key');