Future, Async, Await

JohnKim·2022년 8월 9일
0

flutter

목록 보기
1/7
  1. Future 클래스는 비동기 작업을 할 때 사용한다.
  2. Future는 일정 소요시간 후에 실제 데이터나 에러를 반환한다.
  3. async 클래스는 await 메서드를 가지고 있다.
    • await로 선언된 메서드는 응답이 처리될 때까지 대기

<예제>

void main(){
  showData();
}

// accessData()에 최종적으로 값이 할당될 때까지 기다려야 함으로 async제어자를 추가한다.
void showData() async{
  startTask();
  // accessData()에 output이 생겼기 때문에 account 변수에 output을 할당한다.
  String? account = await accessData();
  // 위의 할당값을 fetchData에 전달한다.
  fetchData(account!);
}

void startTask(){
  String info1 = '요청수행 시작';
  print(info1);
}

// void 타입이면 아무것도 리턴하지 않으므로 accessData함수의 타입형을
// String으로 변경해준다.
Future<String?> accessData() async{
  String? account;
  Duration time = Duration(seconds: 3);
  if(time.inSeconds > 2) {
  
  // await를 붙임으로써 Future.delayed 실행이 끝날때까지 기다리라는 명령을 내린다.
    await Future.delayed(time, (){
      account = '8,500만원';
      print(account);
    });
  } else {
    String info2 = '데이터를 가져왔습니다';
    print(info2);
  }
  return account;
}

// fetchData가 accessData함수의 값을 전달받을 수 있도록 String 인풋을 설정해준다.
void fetchData(String account){
  String info3 = '잔액은 $account 입니다.';
  print(info3);
}

async, await를 사용하지 않는다면 accessData()가 먼저 계산되고 fetchData()가 실행되어야 하는데 그렇지 못하게 된다.

결과

요청수행 시작
잔액은 null 입니다
8,500만원

그래서 accessData 함수를 비동기 함수로 변경해 주어야 Future.delayed가 수행될 때 까지 accessData 자체도 딜레이 시킬 수 있다.

리턴할 accoun는 String data이므로 Future< String> 으로 작성한다.

profile
Developer

0개의 댓글