댓글을 작성하려면 로그인이 필요합니다.
아직 작성된 댓글이 없어요. 첫 댓글을 남겨주세요!

자바스크립트에서 크게 3번에 걸쳐 비동기 처리 기술이 발전되었다.
// 콜백 지옥 예시
getUser(1, function (user) {
getPosts(user.id, function (posts) {
getComments(posts[0].id, function (comments) {
console.log(comments);
// 점점 깊어지는 중첩...
});
});
});
.then()을 붙여서 성공 응답을 받는다..catch()를 붙여서 에러 처리 방식을 작성한다..then()으로 넘어간다.catch()로 넘어간다// Promise 체인 방식
getUser(1)
.then((user) => getPosts(user.id))
.then((posts) => getComments(posts[0].id))
.then((comments) => console.log(comments))
.catch((error) => console.error(error));
.then()으로 이어지기 때문에 훨씬 읽기 쉽다.여러 비동기 작업을 동시에 실행해야 하는 경우 Promise의 동시 처리 메서드를 사용한다.
엄밀히 말하면 "병렬(parallel)"이 아니라 "동시(concurrent)" 에 가깝다. 진짜 병렬은 여러 스레드가 동시에 작업하는 것인데, JS는 싱글 스레드라 그건 불가능하다. 실제로는 JS 엔진이 여러 요청을 연달아 Web API에 넘기고, 브라우저의 네트워크 레이어가 HTTP 요청을 동시에 처리하는 방식이다.
// 순차 실행 — 총 3초 (1초 + 1초 + 1초)
const a = await getA(); // 1초 기다림
const b = await getB(); // 그 다음 1초 기다림
const c = await getC(); // 그 다음 1초 기다림
// 동시 실행 — 총 1초 (셋 다 동시에 출발)
const [a, b, c] = await Promise.all([
getA(),
getB(),
getC()
]);
Promise.all은 셋 다 동시에 출발시키고 전부 끝날 때까지 기다린다.const [user, posts, comments] = await Promise.all([
getUser(1),
getPosts(1),
getComments(1)
]);
// 셋 중 하나라도 실패하면 catch로 빠진다
const results = await Promise.allSettled([
getUser(1),
getPosts(1),
getComments(1)
]);
// results: [{ status: "fulfilled", value: ... }, { status: "rejected", reason: ... }, ...]
async를 붙이고, 그 안에 오래 걸리는 비동기 작업 앞에 await를 명시한다.// async/await 방식
async function loadComments() {
const user = await getUser(1);
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
console.log(comments);
}
.catch()로 에러를 잡지만, async/await는 try/catch로 에러를 잡는다.async function loadComments() {
try {
const user = await getUser(1);
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
console.log(comments);
} catch (error) {
console.error(error);
}
}
| Callback | Promise | async/await | |
|---|---|---|---|
| 가독성 | 중첩이 깊어짐 (콜백 지옥) | 체인 방식으로 개선 | 동기 코드처럼 직관적 |
| 에러 처리 | 각 콜백마다 개별 처리 | .catch() | try/catch |
| 동시 처리 | 직접 구현 필요 | Promise.all / allSettled | Promise.all + await |
자바스크립트의 비동기 처리는 Callback → Promise → async/await 순으로 발전해 왔습니다. Callback은 가장 초기 방식이지만 중첩이 깊어지는 콜백 지옥 문제가 있었고, 이를 해결하기 위해 Promise가 등장하여
.then()체인 방식으로 가독성을 개선했습니다. Promise에는 Pending(대기), Fulfilled(이행), Rejected(거부) 세 가지 상태가 있습니다. async/await는 Promise의 문법적 설탕으로, 내부적으로는 Promise 기반이지만 마치 동기 코드처럼 위에서 아래로 읽을 수 있어 가장 직관적입니다. 에러 처리는 Promise가.catch()를 사용하는 반면, async/await는 동기 코드와 동일한try/catch를 사용합니다. 또한 여러 비동기 작업을 동시에 실행해야 할 때는Promise.all이나Promise.allSettled를 활용할 수 있는데, 이는 엄밀히 말하면 병렬이 아니라 동시(concurrent) 처리입니다. JS 엔진이 여러 요청을 Web API에 넘기고, 브라우저의 네트워크 레이어가 동시에 처리하는 방식이기 때문입니다.