Course contentsShow
← JavaScript
Lesson 463 of 2,72312. Higher-Order FunctionsFree lesson

Reduce with Async Operations

How to use reduce with promises to process items sequentially, and why this pattern can be tricky.

Reduce with Async Operations

What you'll learn: How to use reduce with promises to process items sequentially, and why this pattern requires careful handling.

The Challenge

When you use reduce with asynchronous operations (like API calls or file reads), you need to return promises from your reducer function and properly chain them. Unlike map, which can handle multiple promises in parallel, reduce processes items one at a time in sequence.

How It Works

The trick is to make your accumulator a promise that resolves to the value you're building. Each iteration must wait for the previous promise to resolve before continuing:

const urls = ['api/1', 'api/2', 'api/3'];

// Sequential async processing
const result = await urls.reduce(async (promiseAcc, url) => {
  const acc = await promiseAcc;  // Wait for previous operation
  const response = await fetch(url);  // Then do current operation
  return acc + response.data;
}, Promise.resolve(0));  // Start with a resolved promise

Why This Pattern Is Tricky

  1. You must await the accumulator at the start of each iteration
  2. The initial value must be a resolved promise (Promise.resolve(...))
  3. Your reducer must be async (or explicitly return promises)
  4. It's slower than parallel operations because items wait their turn

When to Use It

Use reduce with async when order matters or you need sequential processing (like rate-limited APIs). For parallel async operations, Promise.all with map is usually faster and simpler.

Key Takeaway: Using reduce with async operations requires awaiting the accumulator and starting with Promise.resolve(), but consider if sequential processing is truly necessary—parallel alternatives are often better.