Reputation: 3
the result[] will be executed before the data is ready. i even tried to solve the problem with promise but also not successfull..
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)
});
};
Upvotes: 0
Views: 915
Reputation: 83163
The following should work (untested):
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 });
})
};
You need to manage the parallel documents fetches with Promise.all()
and chain the different Promises returned by Promise.all()
in order to send back the response only when all those asynchronous operations are completed. In your current code, you are sending back the response before those asynchronous operations are completed.
Also, you may need to fine tune this code in order to check that the different snapshots Arrays are not empty. This part is up to you!
Upvotes: 2