Course contentsShow
← JavaScript
Lesson 1374 of 2,72330. Async/AwaitFree lesson

Combining Map with Promise.all

Transform an array into parallel async operations using map to create promises, then await Promise.all.

Combining Map with Promise.all

You'll learn how to transform an array of values into an array of promises that all execute in parallel.

The Core Pattern

When you have an array of items that each need an async operation, you can use .map() to create an array of promises, then await Promise.all() to execute them all concurrently and collect the results.

Here's the idea: .map() synchronously iterates over your array and returns a new array. If you map each item to an async operation (like a fetch or database call), you get an array of promises. Promise.all() then runs all those promises in parallel and gives you back an array of resolved values in the same order.

Why This Works

Think of it like assigning tasks to multiple workers simultaneously rather than one at a time. You give each worker their job (.map() creates the promises), then wait for everyone to finish (Promise.all() awaits all results).

async function fetchAllUsers(userIds) {
  // Map creates array of promises (all start immediately)
  const promises = userIds.map(id => fetchUser(id));
  
  // Promise.all waits for all to complete
  const users = await Promise.all(promises);
  
  return users;
}

You can also write it inline:

async function fetchAllUsers(userIds) {
  const users = await Promise.all(
    userIds.map(id => fetchUser(id))
  );
  return users;
}

This is the idiomatic JavaScript way to "loop" over async operations in parallel. Each fetchUser(id) starts executing immediately when .map() runs, so all requests happen concurrently.

Key Takeaway: Use .map() to transform each array element into a promise, then await Promise.all() to execute them all in parallel and collect the results—this is the standard pattern for concurrent operations over arrays.