[JavaScript] Promise란?
비동기 작업의 완료 또는 실패를 나타내는 객체.
JavaScript에서 비동기 코드를 작성할 때 예전에는 콜백 함수를 사용했지만 콜백 중첩 문제가 발생함.
이를 해결하기 위해 Promise 도입.
1. Promise의 기본 구조
const promise = new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("성공! 🎉");
} else {
reject("실패! ❌");
}
});
promise
.then(result => console.log("결과:", result))
.catch(error => console.log("에러:", error));
• Promise는 resolve(성공) 또는 reject(실패)를 호출하는 비동기 작업을 감싸는 객체.
• .then() → 성공했을 때 실행되는 코드
• .catch() → 실패했을 때 실행되는 코드
2. Promise의 3가지 상태
1. Pending (대기 중) → Promise가 실행되었지만 결과가 없는 상태
2. Fulfilled (성공) → resolve()가 호출되어 성공한 상태
3. Rejected (실패) → reject()가 호출되어 실패한 상태
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("완료!");
}, 2000);
});
console.log(myPromise); // Pending 상태
myPromise.then(console.log); // 2초 후 "완료!" 출력
3. then()과 catch()
비동기 작업이 성공하거나 실패했을 때 실행할 코드를 then()과 catch()로 작성할 수 있다.
function fetchData(success) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (success) {
resolve("데이터를 성공적으로 가져왔습니다!");
} else {
reject("데이터를 가져오는 데 실패했습니다.");
}
}, 1000);
});
}
fetchData(true)
.then(data => console.log("✅", data)) // 성공하면 실행
.catch(error => console.log("❌", error)); // 실패하면 실행
4. Promise.all() (여러 개의 Promise 처리)
여러 개의 비동기 작업을 동시에 실행하고, 모두 완료될 때까지 기다릴 때 Promise.all() 사용.
const p1 = new Promise(resolve => setTimeout(() => resolve("첫 번째 완료!"), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve("두 번째 완료!"), 2000));
const p3 = new Promise(resolve => setTimeout(() => resolve("세 번째 완료!"), 3000));
Promise.all([p1, p2, p3])
.then(results => console.log(results))
.catch(error => console.log("에러 발생:", error));
👉 3초 후 ["첫 번째 완료!", "두 번째 완료!", "세 번째 완료!"] 출력됨.
5. Promise와 async/await 비교
Promise.then() 방식
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("데이터 도착!"), 2000);
});
}
fetchData().then(data => console.log(data));
async/await 방식
async function getData() {
let data = await fetchData();
console.log(data);
}
getData();
async/await을 사용하면 코드가 더 직관적으로 읽히고 가독성이 좋아진다.
6. Promise 정리
✔ Promise는 비동기 작업을 처리하는 객체
✔ resolve() → 성공 / reject() → 실패
✔ .then() → 성공 시 실행 / .catch() → 실패 시 실행
✔ Promise.all()을 사용하면 여러 개의 Promise를 병렬로 실행 가능
✔ async/await을 사용하면 Promise 코드를 더 간결하게 작성 가능
Promise는 비동기 작업을 깔끔하고 체계적으로 관리하는 도구이다.