1. Promise란?
Promise는 자바스크립트에서 비동기 작업의 완료(또는 실패)를 나타내는 객체입니다.
즉,
“나중에 결과가 생길 거야!”
라고 ‘약속(promise)’하는 객체예요.
예를 들어, 서버에서 데이터를 불러오는 코드가 있을 때
데이터를 기다리는 동안 다른 코드가 멈추지 않게 비동기로 처리합니다.
2. Promise의 상태(State)
Promise는 항상 세 가지 상태 중 하나를 가집니다:
| 상태 | 의미 | 전환 조건 |
| pending | 대기 중 | 아직 결과가 정해지지 않음 |
| fulfilled | 성공 | resolve() 호출됨 |
| rejected | 실패 | reject() 호출됨 |
3. 기본 사용법
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("성공!");
} else {
reject("실패...");
}
});
myPromise
.then((result) => {
console.log(result); // 성공 시 실행
})
.catch((error) => {
console.error(error); // 실패 시 실행
})
.finally(() => {
console.log("항상 실행됨");
});
실행 순서
1️⃣ new Promise() 생성 → pending 상태
2️⃣ resolve() 호출 → fulfilled 상태
3️⃣ .then() 실행
4️⃣ .catch()는 reject일 때만 실행
5️⃣ .finally()는 항상 실행됨
4. 비동기 예제 (예: API 요청 흉내)
function fetchData() {
return new Promise((resolve) => {
console.log("데이터 요청 중...");
setTimeout(() => {
resolve("서버 데이터 도착 ✅");
}, 2000);
});
}
fetchData().then((data) => console.log(data));
출력 결과:
데이터 요청 중...
(2초 후)
서버 데이터 도착 ✅
→ 코드가 블로킹되지 않고 비동기적으로 처리됩니다.
5. then 체이닝 (연속 처리)
new Promise((resolve) => resolve(1))
.then((num) => num + 1)
.then((num) => num * 3)
.then((num) => console.log(num)); // 6
👉 각 then()은 이전 then()의 반환값을 다음 then()으로 전달합니다.
6. 에러 처리
new Promise((resolve, reject) => {
reject("문제 발생!");
})
.then(() => console.log("성공"))
.catch((err) => console.error("에러:", err))
.finally(() => console.log("끝"));
출력:
에러: 문제 발생!
끝
catch()는 중간 then()에서 발생한 오류도 잡습니다.
finally()는 성공/실패 상관없이 항상 실행됩니다.
7. async / await (Promise를 더 쉽게 쓰는 문법)
async/await는 Promise 기반의 문법적 설탕(Syntactic Sugar) 입니다.
즉, Promise를 더 읽기 쉽게 표현하는 문법이에요.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("✅ 데이터 도착"), 2000);
});
}
async function getData() {
console.log("요청 시작");
const result = await fetchData(); // Promise 완료까지 대기
console.log(result);
console.log("요청 끝");
}
getData();
출력 결과:
요청 시작
(2초 후)
✅ 데이터 도착
요청 끝
await은 Promise가 resolve될 때까지 기다렸다가 결과를 반환합니다.
→ 비동기 코드가 마치 동기 코드처럼 읽히게 만들어 줍니다.
8. Promise.all / Promise.race
여러 비동기 작업을 동시에 실행할 때 유용합니다.
Promise.all
모든 작업이 끝나야 결과 반환
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]).then((values) => console.log(values)); // [1, 2, 3]
Promise.race
가장 먼저 끝난 Promise의 결과만 반환
Promise.race([
new Promise((r) => setTimeout(() => r("A"), 1000)),
new Promise((r) => setTimeout(() => r("B"), 500)),
]).then(console.log); // "B"
정리
| 개념 | 설명 |
| Promise | 비동기 작업의 결과를 나타내는 객체 |
| 상태 | pending → fulfilled or rejected |
| 주요 메서드 | .then(), .catch(), .finally() |
| 체이닝 | 여러 비동기 작업을 순서대로 연결 |
| async/await | Promise를 동기처럼 읽기 쉽게 처리 |
| Promise.all | 여러 Promise를 병렬로 처리 |
| Promise.race | 가장 먼저 끝난 Promise의 결과 반환 |
'Coding Study > FrontEnd Study Note' 카테고리의 다른 글
| 함수 선언식과 함수 표현식의 차이점 (0) | 2025.11.13 |
|---|---|
| ES6에 대해서 (0) | 2025.11.13 |
| useEffect가 호출되는 시점 (0) | 2025.11.07 |
| 시맨틱 마크업이란 무엇이며, 왜 중요한가? (0) | 2025.11.05 |
| undefined와 null의 차이점 (0) | 2025.11.05 |