-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathtransaction_promise.js
More file actions
34 lines (29 loc) · 1009 Bytes
/
transaction_promise.js
File metadata and controls
34 lines (29 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// This snippet file was generated by processing the source file:
// ./firestore-next/test.firestore.js
//
// To update the snippets in this file, edit the source and then run
// 'npm run snippets'.
// [START transaction_promise_modular]
import { doc, runTransaction } from "firebase/firestore";
// Create a reference to the SF doc.
const sfDocRef = doc(db, "cities", "SF");
try {
const newPopulation = await runTransaction(db, async (transaction) => {
const sfDoc = await transaction.get(sfDocRef);
if (!sfDoc.exists()) {
throw "Document does not exist!";
}
const newPop = sfDoc.data().population + 1;
if (newPop <= 1000000) {
transaction.update(sfDocRef, { population: newPop });
return newPop;
} else {
return Promise.reject("Sorry! Population is too big");
}
});
console.log("Population increased to ", newPopulation);
} catch (e) {
// This will be a "population is too big" error.
console.error(e);
}
// [END transaction_promise_modular]