I have the following code. The idea is that it will create a record in the groups
collection. If successful, then it should create a record in a different collection – the groups_UID
collection. Is this the correct way to do this? I feel like it might be wrong because async/await
are normally used separately from .then()
, right? Or maybe I’m just misremembering something here.
await docRef.set({
'adminUID': currentUID,
'adminUsername': currentUsername,
'createDate': timestamp,
'groupID': groupID,
'groupName': groupName,
}).then((value) async {
print('##MyApp## database createGroupFS groups record added');
CollectionReference groupsUIDCollection = firestore.collection('groups_' + currentUID);
final groupsUIDDocRef = groupsUIDCollection.doc();
await groupsUIDDocRef.set({
'adminUID': currentUID,
'adminUsername': currentUsername,
'createDate': timestamp,
'groupID': groupID,
'groupName': groupName,
}).then((value) {
print('##MyApp## database createGroupFS groups_UID record added');
returnVal = groupID;
}).catchError((error) {
print('##MyApp## database createGroupFS groups_UID ERROR: ' + error.toString());
returnVal = '';
});
}).catchError((error) {
print('##MyApp## database createGroupFS groups ERROR: ' + error.toString());
returnVal = '';
});
2
Answers
You should either use one or another. I prefer using
async/await
withtry/catch
because I find it more readable. So in your example solution would be:you should use
try/catch
as it will give you more flexibility when theawaited
function throws error.the syntax should be,