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
384

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.

  1. Why does adding await before the update operation prevent the update?
  2. Is it safe to not wait for updates and do it asynchronously like in the first example?


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 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.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!