Reputation: 3081
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?
Upvotes: 1
Views: 564
Reputation: 83058
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
.
Upvotes: 2
Reputation: 191
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
Upvotes: 0