In Firebase Cloud Functions, is it possible to safely update a document asynchronously without waiting for it to return?
P粉043432210
P粉043432210 2023-08-17 14:53:58
0
1
466
<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>
P粉043432210
P粉043432210

reply all(1)
P粉409742142

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 after all asynchronous work has completed (or wait for every promise 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 the documentation about this.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template