在服务器端使用 Firebase/Firestore 获取多个数据 (nextjs/apiRoutes) =问题 =在数据准备就绪之前输出 =>



结果[]将在数据准备就绪之前执行。 我什至试图用承诺解决问题,但也没有成功。

import { firestore } from "../../../firebase";
export default (req, res) => {
firestore
.collection("category-filters")
.where(req.query.categoryKey, "==", true)
.get()
.then(querySnapshot => {
let result = [];
querySnapshot.docs.map(doc => {
firestore
.collection("payment-accounts")
.doc(doc.id)
.get()
.then(item => {
if (item.data().creditAmount > 0) {
firestore
.collection("professional-profiles")
.doc(item.id)
.get()
.then(endresult => {
result.push({ id: endresult.id, ...endresult.data() }); // executes successful
});
}
});
});
res.json({ result }); // the data is outputted before the "querySnapshot.docs.map" is executed...
// therefore received a blank array (result)
});
};

以下内容应该有效(未经测试(:

export default (req, res) => {
firestore
.collection("category-filters")
.where(req.query.categoryKey, "==", true)
.get()
.then(querySnapshot => {
const promises = [];
const paymentAccountsRef = firestore.collection("payment-accounts");
querySnapshot.docs.map(doc => {
promises.push(paymentAccountsRef.doc(doc.id).get());
});
return Promise.all(promises);
})
.then(paymentAccountsSnapshotsArray => {
const promises = [];
const professionalProfilesRef = firestore.collection("professional-profiles");
paymentAccountsSnapshotsArray.forEach(snap => {
if (snap.data().creditAmount > 0) {
promises.push(professionalProfilesRef.doc(snap.id).get());
}
});
return Promise.all(promises);
})
.then(professionalProfileSnapshotsArray => {
const results = [];
professionalProfileSnapshotsArray.forEach(snap => {
results.push({ id: snap.id, ...snap.data() });
});
res.json({ results });
})
};

您需要使用Promise.all()管理并行文档提取,并链接Promise.all()返回的不同 Promises,以便仅在所有这些异步操作完成后发回响应。在当前代码中,您将在这些异步操作完成之前发回响应。


此外,您可能需要微调此代码,以检查不同的快照数组是否为空。这部分取决于你!

最新更新