![](/img/trans.png)
[英]Flutter - how to trigger a function after the async function is completed
[英]If my async function successfully completed, is this the correct way to then do something else?
我有以下代码。 这个想法是它将在groups
集合中创建一条记录。 如果成功,那么它应该在不同的集合中创建一条记录 - groups_UID
集合。 这是正确的方法吗? 我觉得这可能是错误的,因为async/await
通常与.then()
分开使用,对吧? 或者,也许我只是在这里记错了一些东西。
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 = '';
});
您应该使用一个或另一个。 我更喜欢将async/await
与try/catch
一起使用,因为我发现它更具可读性。 所以在你的示例解决方案中是:
try {
// if it fails it goes to the catch part
final res = await docRef.set({
'adminUID': currentUID,
'adminUsername': currentUsername,
'createDate': timestamp,
'groupID': groupID,
'groupName': groupName,
});
// it will continue going on success
print('##MyApp## database createGroupFS groups record added');
CollectionReference groupsUIDCollection =
firestore.collection('groups_' + currentUID);
final groupsUIDDocRef = groupsUIDCollection.doc();
try {
// same thing here
final res2 = await groupsUIDDocRef.set({
'adminUID': currentUID,
'adminUsername': currentUsername,
'createDate': timestamp,
'groupID': groupID,
'groupName': groupName,
});
// success
print('##MyApp## database createGroupFS groups_UID record added');
returnVal = groupID;
} catch (error) {
// error happened on groupsUIDDocRef.set
print('##MyApp## database createGroupFS groups_UID ERROR: ' +
error.toString());
returnVal = '';
}
} catch (error) {
// error happened on docRef.set
print(
'##MyApp## database createGroupFS groups ERROR: ' + error.toString());
returnVal = '';
}
您应该使用try/catch
,因为它会在awaited
的 function 抛出错误时为您提供更大的灵活性。
语法应该是
try{
var result= await someFunction();
//perform action
}catch(e,stacktrace){
//handle error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.