본문 바로가기

Flutter

[Flutter]Future, async, await

728x90

Future

- 비동기 방식으로 미래의 어느 시점에 완성되어서 실제적인 데이터 또는 에러를 반환한다.

- uncompleted 또는 completed의 두 가지 상태를 가질 수 있다.

 

처리 순서

1. 코드에 Future 객체를 호출하면 Dart에 의해 내부적인 배열에 등록된다.

2. Future에 관련되어 실행되어야 할 코드들이 이벤트 큐(대기열)에 등록된다.

3. uncompleted future 객체가 반환된다.

    → 비동기 작업이 완료되거나 에러가 발생할 것을 기다린다.

4. Synchronous(동기) 방식으로 실행되어야 할 코드들이 먼저 실행된다.

5. completed future

   → Future 작업 완료: 비동기 작업이 성공하면 실제적인 data 또는 에러와 함께 완료된다.

 

void main() {
  
  print('Before the future'); // 1
  
  Future((){
    print('Running the future'); //3
    
  }).then((_){
    print('Future is complete'); // 4
  });
  
  print('After the future'); // 2
  
}

// 출력 결과
// Before the future
// After the future
// Running the future
// Future is complete

 

이해한 바를 그림으로 정리해 보았다.

 

 

 

 

async / await

- async, await 키워드로 비동기 함수임을 정의한다.

- 함수명 뒤에 async 키워드를 사용여 비동기 함수를 만들면 await 키워드를 사용할 수 있다.

 

처리 순서

1. await 키워드를 만날 때까지 synchronous 방식으로 코드 처리

2. await 키워드를 만나면 future가 완료될 때까지 대기

3. future가 완료되면 바로 다음 코드들을 실행

 

Future<String> createOrderMessage() async {
  print('Awaiting user order...'); // 2
  var order = await fetchUserOrder();
  return 'Your order is : $order'; // 3
}

Future<String> fetchUserOrder() {  
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Large Latte'
  );
}

// fetchUserOrder의 값이 할당된 후 
// createOrderMessage()의 값이 출력되어야 하므로
// main()에도 async와 await 를 붙여준다.
void main() async {
  print('Fetching user order...'); // 1
  print(await createOrderMessage());
  print('Your order is completed'); //4
}

// 출력 결과
// Fetching user order...
// Awaiting user order...
// Your order is : Large Latte
// Your order is completed

 

 

심화 문제

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

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

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

methodC(String from) async {
  print('C starts 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 starts
// C starts from B
// C end from B
// B end
// C starts 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

 

 

 

<참고>

https://youtu.be/HjhPhAUPHos

https://dart.dev/codelabs/async-await#what-is-a-future

 

Asynchronous programming: futures, async, await

Learn about and practice writing asynchronous code in DartPad!

dart.dev

 

 

 

728x90