## async · await 란? async · await란 ES2017(ES8)에서 도입된 문법으로 [[Promise]] 기반의 비동기 코드를 **좀 더 동기적으로, 직관적으로** 사용할 수 있게 하는 문법이다. (syntax sugar) ```javascript async function fetchUserData() { const response = await fetch('/api/user'); const data = await response.json(); console.log(data); } ``` ## await 의 동작 방식 `await`은 `async` 함수 내부에서만 사용 가능한 키워드이다. `await`은 Promise가 resolve 혹은 reject 될 때 까지 **해당 줄에서 코드 실행을 정지**하도록 한다. ```javascript async function sequential() { const a = await fetchA(); const b = await fetchB(); // fetchA 끝날 때까지 기다림 } ``` ## Promise와의 차이점 ```javascript // Promise function fetchData() { return fetch('/api/data') .then(response => response.json()) .then(data => { console.log(data); return data; }) .catch(error => { console.error(error); }); } // async · await async function fetchData() { try { const response = await fetch('/api/data'); const data = await response.json(); console.log(data); } catch (error) { console.error(error); } } ``` ### 코드 가독성 - `Promise` : 체이닝으로 인한 들여쓰기와 콜백 구조 => 코드가 복잡함 - `async · await` : 동기 코드와 유사한 직관적인 구조 => 읽기 쉬움 ### 에러 처리 - `Promise` : `.catch()` 메서드 체이닝 사용 - `async · await` : `try-catch` 블록 사용 ## 관련 문서 - [[Promise와 async · await]]