JavaScript Promises 초보자를 위한 설명
Source: Dev.to
🧠 What Problem Do Promises Solve?
프라미스가 해결하는 문제는 무엇인가?
Before promises, we used callbacks for async tasks:
fetchData(function (data) {
processData(data, function (result) {
console.log(result);
});
});
❌ Callback hell → hard to read, hard to maintain
❌ 콜백 지옥 → 읽기 어렵고, 유지보수가 힘듦
A promise is like a placeholder for a value that may not be available yet.
프라미스는 아직 사용 가능하지 않을 수도 있는 값을 위한 자리표시자와 같습니다.
⏳ Promise States
프라미스 상태
A promise can be in three states:
프라미스는 세 가지 상태를 가질 수 있습니다:
- Pending – initial state, waiting for the result
Pending – 초기 상태, 결과를 기다리는 중 - Fulfilled – operation succeeded, value available
Fulfilled – 작업 성공, 값 사용 가능 - Rejected – operation failed, error available
Rejected – 작업 실패, 오류 사용 가능
Pending → Fulfilled or Rejected
⚙️ Basic Promise Lifecycle
기본 프라미스 라이프사이클
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then(result => console.log(result)) // handles success
.catch(error => console.log(error)); // handles failure
Output if success = true
Task completed
success = true인 경우 출력
Task completed
Output if success = false
Task failed
success = false인 경우 출력
Task failed
🔄 Promise Chaining
프라미스 체이닝
Promises can be chained to run multiple async tasks sequentially:
프라미스를 체인하여 여러 비동기 작업을 순차적으로 실행할 수 있습니다:
fetchData()
.then(data => processData(data))
.then(result => console.log(result))
.catch(err => console.error(err));
- Cleaner than nested callbacks → 중첩된 콜백보다 깔끔함
- Easier to read and maintain → 읽기와 유지보수가 더 쉬움
📊 Callback vs Promise
콜백 vs 프라미스
| Feature | Callback | Promise |
|---|---|---|
| 특징 | 콜백 | 프라미스 |
| Readability | Low (nested) | High (linear) |
| 가독성 | 낮음 (중첩) | 높음 (선형) |
| Error handling | Hard | Easy (catch) |
| 오류 처리 | 어려움 | 쉬움 (catch) |
| Async flow | Nested | Chained |
| 비동기 흐름 | 중첩 | 체인 |
| Future value | No | Yes |
| 미래 값 | 없음 | 있음 |
🛠️ Real‑World Example
실제 예제
function fetchUser(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId === 1) {
resolve({ id: 1, name: "Rahul" });
} else {
reject("User not found");
}
}, 1000);
});
}
fetchUser(1)
.then(user => console.log(user.name)) // Rahul
.catch(err => console.log(err));
🧩 Visualizing Promise Lifecycle
프라미스 라이프사이클 시각화
Promise created → pending
↓
(resolve) fulfilled → .then runs
(reject) rejected → .catch runs
프라미스 생성 → 대기중
↓
(resolve) 이행 → .then 실행
(reject) 거부 → .catch 실행
🧠 Key Takeaways
핵심 정리
- Promises represent a value in the future.
프라미스는 미래의 값을 나타냅니다. - They prevent callback hell.
콜백 지옥을 방지합니다. .then()handles success,.catch()handles errors.
.then()은 성공을 처리하고,.catch()는 오류를 처리합니다.- Promises can be chained for sequential async operations.
프라미스는 순차적인 비동기 작업을 위해 체인될 수 있습니다.
🚀 Final Thoughts
마무리 생각
Promises are the foundation of modern asynchronous JavaScript. Once you master them, you’ll be ready for:
프라미스는 현대 비동기 JavaScript의 기반입니다. 이를 마스터하면 다음을 준비할 수 있습니다:
- Async/await syntax
Async/await 구문 - Complex async workflows
복잡한 비동기 워크플로 - Clean, readable, maintainable code
깔끔하고, 가독성 높으며, 유지보수 가능한 코드