In my Firebase Cloud Function file, I have the following local function which performs a document get and update operation before returning some properties.
async function getRandomDocLessThanOperator(seed) { try { const db = admin.firestore(); const snapshot = await db.collection("users").where("random", "<=", seed) .limit(1) .get(); if (snapshot.empty) { return null; // The caller then tries the greater than operator } const doc = snapshot.docs[0]; doc.ref.update({"random": seed}); // Update with new seed return doc.get("uid"); } catch (error) { throw new Error(error); } }
This function works fine, but I'm worried about trying to update the document asynchronously before returning. However, in testing, the documentation was never not updated. However, is it possible that this function times out before the update is complete?
Anyway, to fix the problem, I tried using await
to wait for updates:
const doc = snapshot.docs[0]; await doc.ref.update({"random": seed}); return doc.get("uid");
However, when I do this, the function returns the expected string but does not update the document.
await
before the update operation prevent the update?
It's not clear why your update didn't work (maybe you could use more logging to get a clearer picture of what's going on at runtime). But what I can say for sure is that when using Cloud Functions you must return a promise that resolves afterallasynchronous work has completed (or wait foreverypromise encountered), otherwise The function may be closed before its work is completed. This is a common mistake developers make.
No, this is not "safe" because you have no guarantee that the asynchronous code will continue to run after the function terminates. You must return a promise that is only resolved after all asynchronous work is completed.
Please read thedocumentationabout this.