Firestore异步操作中混用await与.then()是否正确?
代码规范分析与优化建议
你的代码可以正常运行,但写法并不规范——混合使用await和.then()会让异步逻辑的流程变得混乱,可读性、可维护性都很差,还容易埋下潜在的错误隐患。
核心问题点
- 冗余嵌套与流程混乱:明明用了
await来扁平化异步代码,却又嵌套.then()回调,反而回到了“回调地狱”的写法,层级越深越难理清执行顺序。 - 错误处理分散:外层用
.catchError,内层又混合await和.then().catchError,错误处理逻辑分散在不同位置,排查问题时要来回跳转,效率极低。 - 状态赋值逻辑零散:
returnVal的成功/失败赋值分别在不同的回调块里,逻辑不集中,后期修改时容易遗漏。
优化后的代码(统一使用await + try/catch)
try { // 第一步:创建groups集合记录 await docRef.set({ 'adminUID': currentUID, 'adminUsername': currentUsername, 'createDate': timestamp, 'groupID': groupID, 'groupName': groupName, }); print('##MyApp## database createGroupFS groups record added'); // 第二步:创建groups_UID集合记录 CollectionReference groupsUIDCollection = firestore.collection('groups_' + currentUID); final groupsUIDDocRef = groupsUIDCollection.doc(); await groupsUIDDocRef.set({ 'adminUID': currentUID, 'adminUsername': currentUsername, 'createDate': timestamp, 'groupID': groupID, 'groupName': groupName, }); print('##MyApp## database createGroupFS groups_UID record added'); returnVal = groupID; } catch (error) { // 统一处理所有异步操作的错误 print('##MyApp## database createGroupFS ERROR: ' + error.toString()); returnVal = ''; }
额外建议
如果这两个写入操作需要原子性(要么都成功,要么都失败),建议使用Firebase的批量写入功能,避免出现第一个写入成功、第二个失败的不一致情况:
try { WriteBatch batch = firestore.batch(); // 添加groups集合的写入操作到批量任务 batch.set(docRef, { 'adminUID': currentUID, 'adminUsername': currentUsername, 'createDate': timestamp, 'groupID': groupID, 'groupName': groupName, }); // 添加groups_UID集合的写入操作到批量任务 CollectionReference groupsUIDCollection = firestore.collection('groups_' + currentUID); final groupsUIDDocRef = groupsUIDCollection.doc(); batch.set(groupsUIDDocRef, { 'adminUID': currentUID, 'adminUsername': currentUsername, 'createDate': timestamp, 'groupID': groupID, 'groupName': groupName, }); // 执行批量写入 await batch.commit(); print('##MyApp## database createGroupFS both records added successfully'); returnVal = groupID; } catch (error) { print('##MyApp## database createGroupFS BATCH ERROR: ' + error.toString()); returnVal = ''; }
内容的提问来源于stack exchange,提问作者whatwhatwhat
相关产品推荐
相关产品推荐

