JavaScript 비동기 치트시트 (Promise·async/await)
Promise, async/await, Promise.all, try/catch 에러 처리 등 자바스크립트 비동기 패턴을 예제로 정리한 치트시트입니다.
async / await 기본
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
await는 Promise가 끝날 때까지 기다렸다가 결과값을 돌려줍니다. async 함수는 항상 Promise를 반환합니다.
에러 처리
try {
const user = await getUser(1);
console.log(user);
} catch (err) {
console.error('실패:', err.message);
} finally {
console.log('로딩 종료');
}
여러 작업 동시에
| 메서드 | 동작 |
|---|---|
Promise.all([...]) | 모두 성공해야 성공, 하나 실패하면 전체 실패 |
Promise.allSettled([...]) | 각각의 성공/실패를 모두 반환 |
Promise.race([...]) | 가장 먼저 끝난 하나 |
Promise.any([...]) | 가장 먼저 성공한 하나 |
// 순차(느림): 두 요청이 줄 서서 실행
const a = await fetchA();
const b = await fetchB();
// 병렬(빠름): 동시에 시작
const [a, b] = await Promise.all([fetchA(), fetchB()]);
자주 하는 실수
// ✕ forEach는 await를 기다리지 않음
arr.forEach(async (x) => { await save(x); });
// ○ for...of 는 순차로 기다림
for (const x of arr) { await save(x); }
// ○ 병렬로 모두
await Promise.all(arr.map((x) => save(x)));
await는async함수 안에서만 쓸 수 있습니다. 최상위에서 쓰려면 모듈 환경의 top-level await가 필요합니다. 응답 파싱 관련 오류는 Unexpected token '<'을 참고하세요.