我正试图等待两个请求,我从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,
});
};
on('value')
不返回promise,在这里不起作用。它只用于将侦听器附加到查询,并且将无限期地接收结果,直到调用off()
。
相反,您应该使用once('value'(,它只执行一次查询,并在查询完成时返回promise。