동기란 ‘동시에 일어난다’라는 뜻이다
코드의 실행 순서가 예측 가능하다
비동기란 ‘동시에 일어나지 않는다’라는 뜻이다
I/O 작업이나 네트워크 요청같이 시간이 오래걸리는 작업에 유용하다
작업의 완료 순서를 예측할 수 없다
여러 작업을 처리하는 방식에 대한 차이이다
여러 작업을 번갈아가면서 처리하는 것
여러 작업을 실제로 동시에 처리하는 것
파라미터로 함수를 받는 함수이다
여러 개의 중첩된 콜백을 처리할 때 코드 가독성과 유지 관리성이 저하되어 "콜백 지옥" 또는 "파멸의 피라미드"라는 현상이 발생할 수 있다.
동시에 여러가지 비동기 함수를 실행할 수 있다
fetchFirstData()
.then((firstResult) {
print("첫 번째 데이터: $firstResult");
return fetchSecondData(firstResult); // 두 번째 Future 반환
})
.then((secondResult) {
print("두 번째 데이터: $secondResult");
return "처리 완료"; // 일반 값 반환 (자동으로 Future로 변환됨)
})
.then((finalResult) {
print("최종 결과: $finalResult");
});
Future<String> fetchData(String id, int delay) {
return Future.delayed(Duration(seconds: delay), () {
print('${DateTime.now().toString().substring(0, 19)}: 데이터 $id 완료');
return '데이터 $id';
});
}
void main() {
print('${DateTime.now().toString().substring(0, 19)}: 시작');
// 세 개의 비동기 작업을 동시에 시작
// 지연 시간이 다르지만 실행 순서는 예측 불가능
fetchData('A', 2).then((data) => print('결과 A: $data'));
fetchData('B', 1).then((data) => print('결과 B: $data'));
fetchData('C', 3).then((data) => print('결과 C: $data'));
print('${DateTime.now().toString().substring(0, 19)}: 모든 작업 시작됨');
}
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return '데이터';
}
void main() async {
String data = await fetchData();
print(data);
}
Future 클래스에 catchError라는 메소드가 있지만, try-catch문을 사용하는 것을 추천
Future<String> getData() async {
try {
// 데이터를 가져우는 비동기 작업
var data = await _getDataFromAPI();
return data;
} catch (error) {
// 데이터를 가져오는 데 실패했을 때 처리
print('데이터를 가져오는 데 실패했습니다: $error');
return '';
}
}
Future.wait은 모든 처리가 끝날 때까지 기다린다
병렬 프로그래밍은 성능 향상의 장점이 있다