EDIT: I found out that "async" could be added to the function signature, and while the output does go in the proper order, I still get an error that I can't set headers after they are sent, even though I am not setting them anywhere else. I've modified the code to reflect this.
I'm having an issue with my Google Firestore api using ExpressJS. It seems that the result is sent before the Firestore query completes and I'm not sure why, as I'm not doing anything with res
otherwise. It seems that Firestore queries are async but I don't know how to have my endpoint wait for the Firestore data before sending results. Here is my router code:
router.post('/some_endpoint/get_something', async function (req, res) {
console.log("Getting firestore data...")
let db_data = null;
let some_val = req.body.some_val;
let colRef = db.collection("some_collection");
await colRef.where("some_field", "==", some_val)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("Still processing...")
db_data = doc.data()
})
res.json({ <---- This is where it breaks
status: 200,
data: db_data
})
})
.catch(function(error) {
console.log("Error getting doc: ", error);
})
console.log("We're done!")
});
This is the output order (EDIT with new output order):
Getting firestore data...
Still processing...
Error getting doc: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client...
We're done!