In Firebase Cloud Functions, is it possible to safely update a document asynchronously without waiting for it to return?
<p>In my Firebase Cloud Function file, I have the following local function which performs a document get and update operation before returning some properties. </p>
<pre class="brush:php;toolbar:false;">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);
}
}</pre>
<p>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? </p>
<p>Anyway, to fix the problem, I tried using <code>await</code> to wait for updates: </p>
<pre class="brush:php;toolbar:false;">const doc = snapshot.docs[0];
await doc.ref.update({"random": seed});
return doc.get("uid");</pre>
<p>However, when I do this, the function returns the expected string but does not update the document. </p>
<ol>
<li>Why does adding <code>await</code> before the update operation prevent the update? </li>
<li>Is it safe to not wait for updates and do it asynchronously like in the first example? </li>
</ol><p><br /></p>