英文:
How to check if a Firestore `batch.commit()` succeeded or failed (i.e. rolled back)
问题
I'm trying to use firestore batch from the firebase-admin
Node.js library.
And I want to do some other stuff only if the batch write is succeeded. But I can't see any option to check if the batch was successfully committed or was rolled back.
I can't find any documentation regarding this from the official google api docs or the official firebase docs.
My Code:
import {getFirestore} from "firebase-admin/firestore";
const firestore = getFirestore();
const batch = firestore.batch();
batch.update(docRef, {"blah_blah_blah": true});
batch.set(docRef2, {"blah_blah_blah": false});
await batch.commit();
// ... if batch succeeded, do some other stuff
英文:
I'm trying to use firestore batch from the firebase-admin
Node.js library.
And I want to do some other stuff only if the batch write is succeeded. But I can't see any option to check if the batch was successfully committed or was rolled back.
I can't find any documentation regarding this from the official google api docs or the official firebase docs.
My Code:
import {getFirestore} from "firebase-admin/firestore";
const firestore = getFirestore();
const batch = firestore.batch();
batch.update(docRef, {"blah_blah_blah": true});
batch.set(docRef2, {"blah_blah_blah": false});
await batch.commit();
// ... if batch succeeded, do some other stuff
答案1
得分: 4
对于返回Promise的所有函数,比如batch.commit()
,一般的理解是如果在异步执行工作时出现错误,返回的Promise将被拒绝。您可以使用普通的JavaScript错误处理来判断异步函数是否返回了一个被拒绝的Promise,当使用async/await时。
try {
await batch.commit();
}
catch (e) {
// batch.commit() 出现了问题。
// 批处理已回滚。
console.error(e);
}
如果您不使用async/await,也可以在返回的Promise对象上使用catch函数。
如果您需要更多关于JavaScript中处理Promise的错误的帮助,建议在网络上搜索相关主题。Firestore 在这方面没有添加任何特殊功能。
英文:
The general understanding with all functions that return a promise, such as batch.commit()
, is that the returned promise will become rejected if there is an error while performing the work asynchronously. You can use normal JavaScript error handling to find out if an async function returned a promise that was rejected when using async/await.
try {
await batch.commit();
}
catch (e) {
// something failed with batch.commit().
// the batch was rolled back.
console.error(e);
}
You can also use the catch function on the returned promise object if you are not using async/await.
If you need more help on javascript error handling with promises, I suggest doing some web searches on the topic. Firestore is not adding anything special here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论