Home > database >  Flutter & Firestore: How to check the commit() of the batch is a success or not?
Flutter & Firestore: How to check the commit() of the batch is a success or not?

Time:10-14

The basic code is:

Future batchSet() async {
  WriteBatch batch = FirebaseFirestore.instance.batch();
  for (var value in dataList) {
    batch.set(FirebaseFirestore.instance.collection('batch').doc(), {
      'createAt': FieldValue.serverTimestamp(),
      'data': value,
    });
  }
  await batch.commit();
}

How to check the result when committed?

I tried await batch.commit().then((value) {}); but the value type is void, can't do anything with value.

Or I just use this:

try {
    await batch.commit();
  } catch (e) {}

Is this work fine if I use try/catch with only the commit()?

CodePudding user response:

A promise can end in two ways:

  • It can either resolve, in which case its then clause is executed with the result of the call passed as a parameter. In the case of a batch.commit there is indeed no result.
  • Or it can be rejected, in which case its catch clause is executed with an error object to indicate what went wrong.

Since you're using async/await, the then clause is essentially the code in the same code-block right after the awaited call. To catch a rejection, use a try-catch block as you did in your last snippet. The e parameter has information on why the promise/commit failed.

  • Related