⚡️ async / await 완전 정리
목차
🚀 1. async / await란?
비동기 코드를 동기 코드처럼 읽히게 만드는 문법적 설탕(Syntactic Sugar)
→ 즉, Promise를 좀 더 “읽기 쉽게” 쓰기 위한 문법이에요.
기존의 .then(), .catch() 체이닝 대신
try / catch 블록을 활용해 가독성 좋게 비동기 코드를 작성할 수 있습니다.
✨ 2. async 함수의 특징
async 키워드를 함수 앞에 붙이면,
그 함수는 자동으로 Promise를 반환하는 비동기 함수가 됩니다.
async function getData() {
return "Hello";
}
getData().then((res) => console.log(res)); // Hello📌 return 값은 자동으로 Promise.resolve()로 감싸집니다.
async function getNumber() {
return 7;
}
console.log(getNumber()); // Promise { 7 }⏳ 3. await의 역할
await은 Promise가 resolve(성공) 될 때까지 기다립니다.
async function fetchData() {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
console.log(data);
}💬 위 코드는 실제로 이렇게 동작해요 👇
1️⃣ fetch() → Promise 반환
2️⃣ await이 결과가 올 때까지 기다림
3️⃣ 완료되면 res에 응답 객체가 들어감
4️⃣ 그다음 줄(res.json()) 실행
마치 동기 코드처럼 한 줄씩 실행되는 것처럼 보이지만,
실제로는 비동기적으로 처리되고 있어요.
⚠️ 4. async/await의 에러 처리 (try / catch)
.then().catch() 대신 try / catch 블록으로 처리합니다.
async function loadUser() {
try {
const res = await fetch("/api/user");
if (!res.ok) throw new Error("서버 에러!");
const user = await res.json();
console.log("✅ 유저 데이터:", user);
} catch (error) {
console.error("❌ 에러 발생:", error.message);
} finally {
console.log("🔚 요청 종료");
}
}📍 Promise 체이닝보다 훨씬 가독성 좋고 디버깅이 쉬움
🔁 5. 여러 비동기 작업 처리하기
(1) 순차 실행 (await 연속 사용)
async function runTasks() {
const a = await task1();
const b = await task2(a);
const c = await task3(b);
console.log(c);
}👉 이전 결과를 다음 함수에 넘겨야 할 때 유용
(2) 동시에 실행 (Promise.all())
async function runParallel() {
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts(),
]);
console.log(user, posts);
}👉 서로 의존하지 않는 비동기 작업이라면 병렬 실행으로 성능 최적화
⚙️ 6. async/await vs Promise 비교
| 비교 항목 | Promise 체이닝 | async/await |
|---|---|---|
| 문법 형태 | .then().catch() | try / catch |
| 코드 가독성 | 중첩되기 쉬움 | 동기 코드처럼 읽힘 |
| 에러 처리 | .catch() 사용 | try / catch 사용 |
| 병렬 실행 | Promise.all() 필요 | Promise.all() 그대로 사용 가능 |
🧠 7. 핵심 요약
✅ async 함수는 항상 Promise를 반환한다
✅ await은 Promise가 resolve될 때까지 기다린다
✅ 에러 처리는 try / catch로
✅ 여러 작업은 Promise.all()로 병렬 처리 가능
✅ 결국 async/await은 Promise를 더 보기 좋게 감싼 문법이다