Future

Posted by アライさん on 2020年12月31日

异步顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
///执行顺序:4 -> 普通方法 -> 3 -> 2 -> 1

//延迟3秒执行
Future.delayed(Duration(seconds: 3), () => print('异步方法1'));
//普通Future
Future(() {
print('异步方法2');
});
//微任务优先级比普通Future高
Future.microtask(() => print('异步方法3'));
//同步方法,相当于直接调用
Future.sync(() => print('异步方法4'));
print('普通方法');

then、catchError、whenComplete

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Future(() {
print('异步方法');
})
.then((_) => print('运行的Future第一个then'))
.then((_){
print('运行有错误的then');
List a= [];
print(a[2]);
})
.then((_) => print('不会被执行'))
.whenComplete((){
print('whenComplete总会被执行');
List a= [];
print(a[5]);
})
.catchError((error)=>print('捕捉到whenComplete的错误'));