Promise는 비동기 작업의 성공 또는 실패 결과를 나중에 사용할 수 있도록 관리하는 객체로, 콜백 지옥을 해결하고 가독성을 높입니다. new Promise((resolve, reject) => {...})로 생성하며, pending, fulfilled, rejected 세 가지 상태를 가집니다. resolve로 성공 값을, reject로 실패 오류를 전달합니다. 후속 처리 메서드(then, catch, finally)로 결과를 처리하며, Promise.all이나 Promise.allSettled로 병렬 작업을 관리합니다.
Promise는 비동기 작업의 결과를 처리하기 위한 객체로, 콜백 함수의 단점(가독성 저하, 에러 처리 어려움, 중첩 문제)을 해결합니다. Promise는 비동기 작업의 상태와 결과를 캡슐화해 흐름을 명확히 관리합니다.
상태
pending: 비동기 작업이 진행 중인 초기 상태.
fulfilled: resolve 호출로 성공한 상태.
rejected: reject 호출로 실패한 상태.
후속 처리 메서드
then(onFulfilled, onRejected): 성공/실패 콜백 처리
promise.then(
(value) => console.log(value), // "작업 성공!"
(error) => console.error(error)
);
catch: rejected` 상태일 때 호출
promise.catch((error) => console.error(error)); // "작업 실패"
finally: 성공/실패 여부와 관계없이 실행
promise.finally(() => console.log("작업 완료")); // "작업 완료"
API 호출
fetch("https://api.example.com/data")
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
순차적 비동기 처리
function fetchUser(id) {
return fetch(`https://api.example.com/users/${id}`).then((res) => res.json());
}
fetchUser(1)
.then((user) => fetchUser(user.friendId))
.then((friend) => console.log(friend));
병렬 처리
1. Promise.all: 모든 Promise가 성공해야 결과 반환, 하나라도 실패 시 즉시 rejected
Promise.all([
fetch("https://api.example.com/data1"),
fetch("https://api.example.com/data2"),
])
.then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
.then(([data1, data2]) => console.log(data1, data2));
Promise.allSettled([
Promise.resolve("성공"),
Promise.reject(new Error("실패")),
]).then((results) =>
console.log(results)
// [{status: "fulfilled", value: "성공"}, {status: "rejected", reason: Error}]
);
장점
단점
주의점