1// 순차 실행 (느림)
2async function sequentialFetch(userIds) {
3 const users = [];
4 for (const id of userIds) {
5 const user = await fetchUser(id); // 순차 실행
6 users.push(user);
7 }
8 return users;
9}
10
11// 병렬 실행 (빠름)
12async function parallelFetch(userIds) {
13 const promises = userIds.map(id => fetchUser(id));
14 return Promise.all(promises); // 동시 실행
15}
16
17// 에러 처리가 포함된 병렬 실행
18async function safeParallelFetch(userIds) {
19 const results = await Promise.allSettled(
20 userIds.map(id => fetchUser(id))
21 );
22
23 return results.reduce((acc, result, index) => {
24 if (result.status === 'fulfilled') {
25 acc.success.push(result.value);
26 } else {
27 acc.failed.push({ id: userIds[index], error: result.reason });
28 }
29 return acc;
30 }, { success: [], failed: [] });
31}
32
33// 동시 실행 수 제한
34async function limitedParallelFetch(userIds, limit = 3) {
35 const results = [];
36 for (let i = 0; i < userIds.length; i += limit) {
37 const batch = userIds.slice(i, i + limit);
38 const batchResults = await Promise.all(batch.map(fetchUser));
39 results.push(...batchResults);
40 }
41 return results;
42}