推荐答案
// www.javascriptcn.com code example
Future<void> fetchData() async {
Future.delayed(Duration(seconds: 2), () {
throw Exception('Error occurred');
})
.then((value) {
print('Data fetched successfully: $value');
})
.catchError((error) {
print('Error: $error');
})
.whenComplete(() {
print('Future completed');
});
}本题详细解读
1. then 方法
then 方法用于在 Future 完成时执行回调函数。如果 Future 成功完成,then 中的回调函数会被调用,并且会接收到 Future 的结果作为参数。
Future.delayed(Duration(seconds: 2), () {
return 'Data';
}).then((value) {
print('Data fetched successfully: $value');
});2. catchError 方法
catchError 方法用于捕获 Future 执行过程中抛出的异常。如果 Future 执行过程中发生错误,catchError 中的回调函数会被调用,并且会接收到错误信息作为参数。
Future.delayed(Duration(seconds: 2), () {
throw Exception('Error occurred');
}).catchError((error) {
print('Error: $error');
});3. whenComplete 方法
whenComplete 方法用于在 Future 完成时(无论成功还是失败)执行回调函数。这个方法通常用于执行一些清理操作或资源释放。
Future.delayed(Duration(seconds: 2), () {
throw Exception('Error occurred');
}).whenComplete(() {
print('Future completed');
});4. 组合使用
在实际开发中,通常会将 then、catchError 和 whenComplete 组合使用,以便在 Future 完成时执行相应的操作,并在发生错误时进行错误处理。
// www.javascriptcn.com code example
Future.delayed(Duration(seconds: 2), () {
throw Exception('Error occurred');
})
.then((value) {
print('Data fetched successfully: $value');
})
.catchError((error) {
print('Error: $error');
})
.whenComplete(() {
print('Future completed');
});在这个例子中,Future 会在 2 秒后抛出一个异常,catchError 会捕获这个异常并打印错误信息,最后 whenComplete 会执行并打印 "Future completed"。