AniUI Academy

Reduce an array with an async reducer

mediumAsync & Promises+250 XPPractice

Applying a queue of offline edits to a document, or importing rows one at a time so each can see the effect of the previous one, both need a fold where every step waits for the last.

Implement reduceAsync(items, reducer, initial). Starting from initial, call reducer(accumulator, item, index) for each item in order, awaiting the result before moving on, and resolve with the final accumulator. The reducer may return a plain value or a promise. An empty array resolves with initial without calling the reducer. If the reducer throws or rejects, reject with that reason and stop — later items are not processed.

Arguments

itemsArray<T>
The input array to fold.
reducer(acc: U, item: T, index: number) => U | Promise<U>
Called for each item with the accumulator, item, and index.
initialU
The starting value for the accumulator.

Returns

Promise<U> — A promise that resolves with the final accumulator. Rejects on the first failure and stops.

Examples

const total = await reduceAsync(
  [1, 2, 3, 4],
  async (sum, n) => sum + n,
  0
);
// total === 10

Each step awaits the previous accumulator before continuing.

let calls = 0;
const value = await reduceAsync([], async (acc) => { calls++; return acc; }, "untouched");
// value === "untouched", calls === 0 — reducer never ran

Empty input returns initial without invoking the reducer.

What it has to do

  • Process items strictly in order, awaiting each result.
  • Pass (accumulator, item, index) to the reducer.
  • Resolve with initial for an empty array, without calling the reducer.
  • Support reducers that return plain values.
  • Reject on the first failure and stop processing.

Notes

  • Each step must await the previous accumulator — Promise.all + reduce won't work because later steps depend on earlier ones.
  • A rejection halts the fold immediately; subsequent items are not visited.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.