
Firestore 的批量写入操作 (batch.commit()) 是原子性的,这意味着要么所有写入操作都成功执行,要么所有操作都失败回滚。理解如何检测 batch.commit() 的结果对于构建健壮的应用程序至关重要。幸运的是,Firestore 遵循标准的 JavaScript Promise 模式,使得我们可以利用标准的错误处理机制来判断批量写入是否成功。
// 摘要:本文介绍了如何使用 Firebase Admin SDK 中的 Firestore Batch 操作,并提供了一种可靠的方法来检测 `batch.commit()` 操作是否成功完成或因错误回滚。通过标准的 JavaScript Promise 错误处理机制,您可以确保在批量写入成功后执行后续操作,并在出现问题时进行适当的错误处理。
使用 try...catch 块处理异常
当使用 async/await 语法时,最常用的方法是使用 try...catch 块来捕获可能出现的异常。如果 batch.commit() 操作失败,Promise 将被拒绝,从而触发 catch 块中的代码。
以下是一个示例:
import { getFirestore } from "firebase-admin/firestore";
const firestore = getFirestore();
const batch = firestore.batch();
const docRef = firestore.collection("myCollection").doc("doc1");
const docRef2 = firestore.collection("myCollection").doc("doc2");
batch.update(docRef, { "blah_blah_blah": true });
batch.set(docRef2, { "blah_blah_blah": false });
try {
await batch.commit();
// 批量写入成功,执行后续操作
console.log("Batch commit successful!");
// 在这里可以执行其他操作,例如更新本地状态、发送通知等
} catch (e) {
// 批量写入失败,进行错误处理
console.error("Batch commit failed:", e);
// 在这里可以进行错误处理,例如重试、记录日志、通知管理员等
}使用 .catch() 方法处理 Promise 拒绝
如果你没有使用 async/await 语法,你可以使用 Promise 的 .catch() 方法来处理拒绝的情况。
import { getFirestore } from "firebase-admin/firestore";
const firestore = getFirestore();
const batch = firestore.batch();
const docRef = firestore.collection("myCollection").doc("doc1");
const docRef2 = firestore.collection("myCollection").doc("doc2");
batch.update(docRef, { "blah_blah_blah": true });
batch.set(docRef2, { "blah_blah_blah": false });
batch.commit()
.then(() => {
// 批量写入成功,执行后续操作
console.log("Batch commit successful!");
// 在这里可以执行其他操作,例如更新本地状态、发送通知等
})
.catch((e) => {
// 批量写入失败,进行错误处理
console.error("Batch commit failed:", e);
// 在这里可以进行错误处理,例如重试、记录日志、通知管理员等
});注意事项:
总结
通过使用 try...catch 块或 .catch() 方法,你可以有效地检测 Firestore batch.commit() 操作的成功与失败,并根据结果执行相应的操作。理解 Promise 的错误处理机制是编写健壮的 Firestore 应用程序的关键。请务必根据你的应用场景选择合适的错误处理策略,并考虑实现重试机制以提高应用程序的可靠性。
以上就是使用 Firestore Batch Commit 的成功与失败检测的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号