如何检查 Firestore 的 `batch.commit()` 是否成功或失败(即是否回滚)

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月13日 18:37:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定