반응형
Promise.all
Promise.all()은 여러 개의 비동기 작업(Promise)을 동시에 실행하고, 모든 작업이 완료될 때까지 기다리는 JavaScript 메서드입니다
Promise.all 안쓰는 예시
// 유저
async function getUser() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
user: {
userId: "abc@gmail.com",
name: "김철수",
age: 29,
phone: "010-1234-5678",
grade: "VIP",
point: 12500,
createdAt: "2024-03-12T10:20:30Z",
},
});
}, 2000);
});
}
// 상품
async function getOrder() {
return new Promise(async (resolve) => {
await setTimeout(() => {
resolve({
orderId: "ORD-20260526-0001",
orderDate: "2026-05-26T09:30:00Z",
status: "COMPLETED",
payment: {
method: "CARD",
amount: 38900,
currency: "KRW",
},
user: {
userId: "abc@gmail.com",
name: "김철수",
phone: "010-1234-5678",
},
items: [
{
productId: 101,
productName: "무선 키보드",
quantity: 1,
price: 25900,
},
{
productId: 102,
productName: "무선 마우스",
quantity: 1,
price: 13000,
},
],
shipping: {
address: "서울특별시 강남구 테헤란로 123",
deliveryMessage: "문 앞에 놓아주세요.",
},
});
}, 2000);
});
}
// 장바구니
async function getCart() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
cartId: "CART-20260526-001",
totalPrice: 58900,
totalQuantity: 3,
items: [
{
productId: 101,
productName: "무선 키보드",
quantity: 1,
price: 25900,
thumbnail: "https://example.com/images/keyboard.jpg",
},
{
productId: 102,
productName: "무선 마우스",
quantity: 2,
price: 16500,
thumbnail: "https://example.com/images/mouse.jpg",
},
],
});
}, 2000);
});
}
async function getInitData() {
// 한건한건 await를 호출해야 하는 것이 있다.
const userResult = await getUser();
const orderResult = await getOrder();
const cartResult = await getCart();
console.log(userResult, orderResult, cartResult);
}
getInitData에서 한건한건 호출해야하는 것이 단점이다
Promise.all 쓰는 경우
// 똑같은 결과이지만 코드 라인을 줄일 수 있다.
async function getInitData() {
const [userResult, orderResult, cartResult] = await Promise.all([getUser(), getOrder(), getCart()]);
console.log(userResult, orderResult, cartResult);
}
똑같은 결과이지만, 한줄에 모든 것이 처리가 가능하다
Promise.all()의 단점
하나라도 실패하면 전체가 실패한다는 점이 있다.
그래서 상황에 따라 잘 써야 한다
Promise.allSettled()
Promise.allSettled()는 여러 Promise를 동시에 실행하고, 성공하든 실패하든 모든 결과가 끝날 때까지 기다리는 메서드입니다.
Promise.allSettled 사용하는 경우
async function getCart() {
return Promise.reject("장바구니 조회 실패");
}
async function getInitData() {
try {
const results = await Promise.allSettled([getUser(), getOrder(), getCart()]);
// 성공 데이터 필터
const successResults = results.filter((result) => result.status === "fulfilled").map((result) => result.value);
// 실패 데이터 필터
const failResults = results.filter((result) => result.status === "rejected").map((result) => result.reason);
console.log(successResults, failResults);
} catch (error) {
console.error("[getInitData] error : ", error);
}
}
Promise.all과 달리 한개 실패해도 나머지 2개 성공한 경우의 데이터를 리턴해준다.
반응형
'Javascript' 카테고리의 다른 글
| Web-Client DIP(Dependency inversion principle) (0) | 2026.05.15 |
|---|---|
| 😌 DIP (0) | 2026.05.11 |
| Queue으로 작업실행 (0) | 2025.05.19 |
| 💿 상태 패턴 (0) | 2024.11.25 |
| ❄️ 전략 패턴 (1) | 2024.11.19 |
댓글