设计思路
- 封装异步操作:将每个异步操作封装成一个独立的函数,返回
Future
。
- 链式调用:对于有依赖关系的操作,通过
then
方法进行链式调用。
- 并行执行:对于可以并行执行的操作,使用
Future.wait
方法。
- 错误处理与重试:在
catchError
中根据不同的错误类型进行相应的重试策略。
关键代码片段
// 模拟异步操作函数
Future<String> asyncOperation1() async {
// 实际业务逻辑,例如网络请求
await Future.delayed(const Duration(seconds: 1));
return 'result1';
}
Future<String> asyncOperation2(String previousResult) async {
// 依赖前序操作结果的业务逻辑
await Future.delayed(const Duration(seconds: 1));
return '$previousResult - result2';
}
Future<String> asyncOperation3() async {
// 可并行执行的业务逻辑
await Future.delayed(const Duration(seconds: 1));
return 'result3';
}
// 重试函数
Future<T> retry<T>(Future<T> Function() operation, int maxRetries,
{Function(Exception e)? onRetry}) async {
int attempts = 0;
while (attempts < maxRetries) {
try {
return await operation();
} catch (e) {
attempts++;
if (onRetry != null) {
onRetry(e);
}
if (attempts >= maxRetries) {
rethrow;
}
}
}
throw Exception('Max retries reached');
}
void main() {
asyncOperation1()
.then((result1) {
// 并行执行
return Future.wait([
asyncOperation2(result1),
asyncOperation3()
]);
})
.then((results) {
print('Final results: ${results.join(', ')}');
})
.catchError((e) {
if (e is NetworkException) {
// 网络错误重试3次
retry(() => asyncOperation1(), 3, onRetry: (e) {
print('Network error, retrying... $e');
}).then((result1) {
// 后续操作...
}).catchError((e) {
print('Final error after retries: $e');
});
} else if (e is DataFormatException) {
// 数据格式错误不再重试直接提示用户
print('Data format error: $e');
} else {
print('Other error: $e');
}
});
}
// 自定义错误类型
class NetworkException implements Exception {}
class DataFormatException implements Exception {}