Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Firestore Transactions - Is it necessary to await for all transaction actions?

I have read this code in the Firestore documentation:

const cityRef = db.collection('cities').doc('SF');

try {
  const res = await db.runTransaction(async t => {
    const doc = await t.get(cityRef);
    const newPopulation = doc.data().population + 1;
    if (newPopulation <= 1000000) {
      await t.update(cityRef, { population: newPopulation });
      return `Population increased to ${newPopulation}`;
    } else {
      throw 'Sorry! Population is too big.';
    }
  });
  console.log('Transaction success', res);
} catch (e) {
  console.log('Transaction failure:', e);
}

but I can't understand the purpose of awaiting the t.update() of the 8th line.

Wouldn't the code work the same way without awaiting for that 8th line?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I can't understand the purpose of awaiting the t.update() of the 8th line. Wouldn't the code work the same way without awaiting for that 8th line?

You are totally right: the update() method (as well as the set() and delete() ones) is not asynchronous and does not return a Promise, but the Transaction.

about 4 years ago · Juan Pablo Isaza Report

0

When you call js async function you get a Promise object returned, which can tell you about the PromiseState (if function finished it's runtime) and PromiseResult (function's returned value).
The fact that the Promise object has returned does't tell you that the function finished it's mission.
The 'await' keyword makes your code stop until the async function finished running (similar to std::thread::join method).
Using 'await' with a Promise object can tell you for sure that your Promise has resolved, so (if the code didn't throw an exception) the lines after it can run safely, knowing that the async function ran successfully.
The use of the await at the t.update Promise is necessary and you should keep it there, elsewise you may return a success string for a code that still runing and might fail.

Note that the await keyword checks for finished Promise.PromiseState, and evaluates the Promise.PromiseResult value (undefined for non-returning functions)

Read Also:
JavaScript Async on W3Schools
Async Function on MDN

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!