어떤 순서로 함수가 출력될지 예상해보자.
void main() async{
methodA();
await methodB(); //methodB()의 실행이 끝날때까지 그 이하의 코드 실행이 멈춘다.
await methodC('main');
methodD();
}
methodA(){
print('A'); 1
}
methodB() async{
print('B start'); 2
await methodC('B'); // mathodC() 함수의 실행이 끝날때까지 그 이하의 코드 실행이 멈춘다.
print('B end'); 5
}
methodC(String from) async{
print('C start from $from'); 3 6
Future((){
print('C running Future from $from'); 9 11
}).then((_){
print('C end of Future from $from'); 10 12
});
print('C end from $from'); 4 7
}
methodD(){
print('D'); 8
}
Console
A
B start
C start from B
C end from B
B end
C start from main
C end from main
D
C running Future from B
C end of Future from B
C running Future from main
C end of Future from main
ex2)
Future<void> futureTest() async{
await Future.delayed(Duration(seconds: 3))
.then((value){
print('Here comes second');
setState((){
this.result = 'The data is fetched';
print(result);
print('Here comes third');
});
print('Here comes first');
print('Here is the last one');
}
}
Console
Here comes second
The data is fetched
Here comes third
Here comes first
Here is the last one
ex3)
void futureTest(){
Future.delayed(Duration(seconds: 3))
.then((value){
setState((){
this.result = 'The data is fetched';
print(result);
});
});
print('Here comes first');
}
}
Console
Here comes first
The data is fetched