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()?
>Solution :
A promise can end in two ways:
- It can either resolve, in which case its
thenclause is executed with the result of the call passed as a parameter. In the case of abatch.committhere is indeed no result. - Or it can be rejected, in which case its
catchclause 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.