C.W.K.
Stream
Lesson 04 of 05 · published

`Promise.all` 과 Tuple Typing

~8 min · async-promises, promise-all, tuples, concurrency

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Promise.all 이 tuple 보존하는 parallelism."

Promise.all 이 뭐 함

Promise.all([p1, p2, p3]) 가 Promise 배열 (또는 tuple) 받고 모든 입력 Promise resolve 될 때 resolve 하는 Promise 반환. Resolved 값이 같은 순서의 resolved 값 배열.

타입 레벨에서, tuple 전달하면 결과가 tuple 모양 보존: Promise.all([Promise.resolve(1), Promise.resolve('a')])Promise<[number, string]>. 즉 await 후 destructuring 이 각 위치 타입 보존 — `[a, b]` 가 `a: number; b: string` 얻음.

순차 vs 병렬

연속 두 await 호출이 순차 실행. const a = await fa(); const b = await fb() 가 time(fa) + time(fb) 걸림. Promise.all 이 병렬: const [a, b] = await Promise.all([fa(), fb()]) 가 max(time(fa), time(fb)) 걸림.

독립 async 호출엔 Promise.all 이 거의 항상 옳은 수. Compiler 가 너의 호출이 독립인지 알 수 없어 — 그게 너의 일.

실패 행동

Promise.all 이 빨리 reject: 어떤 입력 Promise 든 reject 하면 전체가 그 에러로 reject. '모두 기다리고, 성공과 실패 둘 다 수집' 엔 `Promise.allSettled` 써 (`{ status: 'fulfilled' | 'rejected', value? / reason? }` 배열 반환).

Async 호출이 서로 결과 의존 안 하면, Promise.all 로 병렬 실행. 성능 개선 실제; 타입 ergonomics (tuple 보존) 가 가장 깨끗한 옵션 만들어.

Code

병렬 vs 순차, 타입-안전 tuple 과 함께·typescript
// 순차 — 느림.
async function loadSequential() {
  const user = await fetchUser(1);        // 기다림
  const posts = await fetchPosts(1);      // 그다음 또 기다림
  return { user, posts };
}

// 병렬 — Promise.all 이 tuple typing 보존.
async function loadParallel() {
  const [user, posts] = await Promise.all([
    fetchUser(1),
    fetchPosts(1),
  ]);
  // user: User, posts: Post[] — 위치별 타입 보존
  return { user, posts };
}

// Promise.allSettled — 실패 포함 모든 결과 수집.
async function loadResilient() {
  const results = await Promise.allSettled([fetchUser(1), fetchPosts(1)]);
  // results: [PromiseSettledResult<User>, PromiseSettledResult<Post[]>]
  for (const r of results) {
    if (r.status === 'fulfilled') console.log(r.value);
    else console.error(r.reason);
  }
}

External links

Exercise

3개 순차 fetch 하는 함수를 Promise.all 쓰는 거로 refactor. (performance.now() 와 함께) 차이 측정. 그다음 한 fetch 를 reject 하게 바꾸고 Promise.all 어떻게 행동하는지 관찰 — 에러 메시지 명확해?
Hint
순차가 시간의 합; 병렬이 max. Promise.all 의 rejection 이 첫 rejector 의 reason surface — 더 명확한 에러 attribution 엔 Promise.allSettled 쓰고 각 결과 체크.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.