Flutter

Future, Async, Await

홍박스 2024. 12. 15. 11:06
728x90

Synchronous 방식

순서대로 하나만 하고 후에 다른 하나를 하는 방식

 

Asynchronous 방식 - (Future)

Synchronous 가 끝나고 난 뒤 출력, 여러개를 한번에 하는 방식

 

Future는 객체가 내부적인 배열에 큐 방식으로 등록,

Async는 await 값이 올때까지 기다리기
메서드 통해서 나오는 결과물을 Future, Await 나올때 까지 Synchronous 방식으로 코드 처리

만나면 future가 완료될 때까지 대기, Future 가 완료되면 그 다음코드들을 실행

 

 

 

 

 

 

문제

void main() async {
  methodA();
  await methodB();
  await methodC('main');
  methodD();
}

methodA() {
  print('A');
}

methodB() async {
  print('B start');
  await methodC('B');
  print('B end');
}

methodC(String from) async {
  print('C start from $from');

  Future(() {
    print('C running Future from $from');
  }).then((_) {
    print('C end of Future from $from');
  });

  print('c end from $from');
}

methodD() {
  print('D');
}

 

결과

더보기

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

 

- 출처 코딩셰프 조금매운맛 강좌

728x90

'Flutter' 카테고리의 다른 글

Lifecycle (플러터 생명주기)  (0) 2024.12.15