Async Map

Async Map - Explanation

보통 비동기 O(n) O(n)

Problem Summary

Write an async map function that processes array items with an async callback.

Go to Problem →

Detailed Explanation

이 문제는 **비동기 map**을 구현하여 병렬 비동기 처리를 학습합니다. ## 핵심 개념: 비동기 Map 배열의 각 요소에 비동기 함수를 적용하고 모든 결과를 모읍니다. ### 구현 ```javascript async function asyncMap(arr, callback) { return Promise.all(arr.map(callback)); } ``` ### 왜 이렇게 간단한가? 1. map으로 각 요소에 비동기 콜백 적용 → Promise 배열 2. Promise.all로 모든 Promise 완료 대기 3. 결과 배열 반환 ### 동기 vs 비동기 map ```javascript // 동기 map [1, 2].map(x => x * 2) // [2, 4] // 비동기 map await asyncMap([1, 2], async x => { await delay(100); return x * 2; }); // [2, 4] ``` ### 병렬 vs 순차 처리 ```javascript // 병렬 (동시 실행) await Promise.all(arr.map(asyncFn)); // 순차 (하나씩) for (const item of arr) { await asyncFn(item); } ``` asyncMap은 병렬 처리로 성능을 최적화합니다.

Solution Code

solution.js
async function asyncMap(arr, callback) {
  return Promise.all(arr.map(callback));
}

Key Concepts from This Problem

1. 비동기 map
2. Promise.all
3. 병렬 처리
4. async/await

Common Mistakes

일반 map은 Promise 배열을 반환합니다 - await가 필요합니다
순차 처리가 필요하면 for...of를 사용하세요
에러 처리를 위해 try-catch를 고려하세요

Hints

Hint 1: Promise.all과 map을 조합하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#비동기 #map #Promise.all