【发布时间】:2020-04-09 01:48:06
【问题描述】:
我正在尝试等待两个请求,我从 firebase DB 获取数据并设置为一种状态,
我想在两个请求完成后,将结果数据连接到一个数组中,
所以我尝试在一个数组中推送两个请求,然后使用
> Promise.all(promises).then(()=>this.updateData());
但它没有按预期工作,我可以在控制台中看到 updateData() 在“之前调用”
代码在这里
fetchOrders = async () => {
....
let promises = [];
promises.push(
// First service orders
database()
.ref(
`Providers/CategoriesOrders/${this.state.serviceName[0] ||
this.state.serviceStorage[0]}`,
)
.on('value', this.ordersCallbackOne),
);
promises.push(
// Second service orders
database()
.ref(
`Providers/CategoriesOrders/${this.state.serviceName[1] ||
this.state.serviceStorage[1]}`,
)
.on('value', this.ordersCallbackTwo),
);
Promise.all(promises).then(() => this.updateData());
};
ordersCallbackTwo = snapshot => {
let orderArr = [];
snapshot.forEach(childSnapshot => {
orderArr.push({
snapshotKey: childSnapshot.key,
username: childSnapshot.val().username,
});
});
this.setState({orderServiceTwo: orderArr}, () =>
console.log('2', this.state.orderServiceTwo), // it's log data here
);
};
两个请求完成后我要调用的函数。
updateData = () => {
// if (this.rejectedOrders?.length >= 1) {
// const orders = this.state.orders.filter(
// order => !this.rejectedOrders.some(key => order.snapshotKey === key),
// );
// this.setState({orders, loading: false});
// return;
// }
console.log('ordersOne!', this.state.orderServiceOne); // empty!
const order1IDs = new Set(
this.state.orderServiceOne.map(({snapshotKey}) => snapshotKey),
);
console.log('order1IDs', order1IDs);
const combined = [
...this.state.orderServiceOne,
...this.orderServiceTwo?.filter(
({snapshotKey}) => !order1IDs.has(snapshotKey),
),
];
console.log('combined', combined);
this.setState({
orders: combined,
loading: false,
});
};
【问题讨论】:
-
这
database() .ref( `Providers/CategoriesOrders/${this.state.serviceName[0] || this.state.serviceStorage[0]}`, ) .on('value', this.ordersCallbackOne)是否返回承诺? -
@ZHANGLuyao 我认为是的..
标签: javascript reactjs firebase react-native firebase-realtime-database