반응형
- Future : 비동기(async) 작업을 표현하는 Dart의 핵심 타입
- Future 객체를 통해 실행되는 로직이 나중에 처리되는 것을 확인 가능한 코드
// Future - 비동기 작업의 결과 또는 완료 상태를 나타내는 객체
void main() {
playPcGame();
}
void playPcGame() {
startBoot();
startInternet();
startGame();
}
void startBoot() {
print("boot completed");
}
void startInternet() {
Future.delayed(Duration(seconds: 3), () {
print("internet completed");
});
print('delay step');
}
void startGame() {
print("game completed");
}
- 비동기 함수 구성
Future<void> asyncFunc() async {}
- 이제 비동기 처리를 통해 서버 또는 DB에서 데이터를 Fetch 하고 그 이후에 가져온 값을 처리할 수 있는 형태를 생각해본다.
- 이때, await를 통해 다음 동기 프로세스의 대기를 요청할 수 있다.
void loadData() async {
String result = await fetchData();
print(result);
}
- await fetchData()를 만나면, Dart는 fetchData()가 끝날 때까지 대기한다.
- fetchData()가 완료되면, 그 결과를 result에 담고 이후 코드를 실행
- await은 항상 async 함수 안에서만 사용 가능하다.
- 아래와 같이 구성된 로직에서는 await을 통해 중간에 delay 처리로 인한 대기가 있더라도 반드시 그 순서가 지켜지게 된다.
void main() {
playPcGame();
}
Future<void> playPcGame() async {
startBoot();
await startInternet();
startGame();
}
void startBoot() {
print("boot completed");
}
Future<void> startInternet() async {
await Future.delayed(Duration(seconds: 3), () {
print("internet completed");
});
print('delay step');
}
void startGame() {
print("game completed");
}
- 또한 await 말고, then을 통해 Future에서 결과 값에 대한 처리가 가능하기도 하다.
getName().then((name) {
print("받은 이름: $name");
}).catchError((error) {
print("에러 발생: $error");
});
반응형