面试题答案
一键面试import 'dart:async';
Future<String> asyncOperation1() async {
// 模拟异步操作,这里返回一个成功的结果
await Future.delayed(const Duration(seconds: 1));
return '操作1成功';
}
Future<String> asyncOperation2() async {
// 模拟异步操作,这里抛出一个错误
await Future.delayed(const Duration(seconds: 1));
throw Exception('操作2失败');
}
Future<String> asyncOperation3() async {
// 模拟异步操作,这里返回一个成功的结果
await Future.delayed(const Duration(seconds: 1));
return '操作3成功';
}
Future<void> performAsyncOperations() async {
try {
final result1 = await asyncOperation1();
print(result1);
final result2 = await asyncOperation2();
print(result2);
final result3 = await asyncOperation3();
print(result3);
} catch (e) {
// 捕获并处理错误
print('发生错误: $e');
}
}
void main() {
performAsyncOperations();
}
在上述代码中:
asyncOperation1
、asyncOperation2
和asyncOperation3
模拟了三个异步操作。performAsyncOperations
函数中使用try-catch
块来捕获异步操作中抛出的错误。- 当
asyncOperation2
抛出错误时,asyncOperation3
不会执行,错误会被catch
块捕获并处理。