[Dart] 동기(sync), 비동기(async)

김동욱·2023년 12월 18일

동기 (sync)

순차적 코드 실행
이전 작업의 실행이 완료되어야 다음 작업 실행

비동기 (async)

임의의 순서로 또는 동시에 작업 실행
비동기를 처리하는 방법
1. 콜백
2. Future
3. async - await

비동기 코드 예시

Future

미래에 완료되는 객체
Javascript Promise 대응

Future<String> name;
Future<int> number;
Future<Person> person;

// delayed 함수로 임의시간 부여
var delay = Future.delayed(Duration(seconds: 5));

Future 함수 앞에 async 키워드
대기하고 싶은 비동기 함수 실행시 await 키워드

then

Future 함수 결과는 then() 함수로 리턴

save(user)
	.then((_) => sendEmail(user))
	.then((_) => getResult(user))
	.then((value) => print(value));

불필요한 인자는 _ 를 쓰는것이 관례

Future 핸들링

delay
	.then((value) => print(value))
	.catchError((err) => print(err));

Future 예외 발생

save(user)
	.then((_) => sendEmail(user))
    .catchError((err) => throw Exception('error send email'))
    .then((_) => getResult(user));

Future whenComplete()

성공 실패 여부 관계없이 실행

save(user)
	.then((_) => sendEmail(user))
    .catchError((err) => throw Exception('error send email'))
    .whenComplete(() => print('반드시실행'));

async - await

await 키워드는 해당 Future 가 끝날 때까지 함수 실행 대기

profile
백엔드 개발자

0개의 댓글