Skip to curriculum
Jump to the editor

12.7. Map over items with an async function

Medium
Topics
20–30 min

items.map(fn) is synchronous: give it an async fn and you get an array of promises, not of results. Real code needs two async versions of map. One starts every call at once and waits for all of them, which is fastest when the calls are independent: load the details of ten products. The other runs one call at a time, which is needed when each call must finish before the next begins: apply database migrations in order, or stay gentle with a rate-limited API.

Write both in map-async.js, without the built-in promise combinators.

Signature

JAVASCRIPT
function mapAsync(items, fn)   // returns a Promise of an array
function mapSeries(items, fn)  // returns a Promise of an array
  • items: any iterable: an array, a Set, a generator.
  • fn(item, index): returns a promise or a plain value.
  • Both fulfill with the results in input order.

Requirements

mapAsync:

  1. Returns a promise, and calls fn(item, index) for every item during the call, without waiting for any result.
  2. Fulfills when the last result arrives, with the results in input order, whatever order they finished in. undefined and falsy results keep their places.
  3. Rejects with the first rejection as soon as it happens. If fn throws, the promise rejects with what it threw; mapAsync itself does not throw.
  4. Plain values from fn count as results; an empty iterable fulfills with []; holes in an array are passed to fn as undefined.
  5. Promise.all, Promise.allSettled, Promise.race and Promise.any are not used (the tests replace them).

mapSeries:

  1. Returns a promise and calls fn for the first item during the call. Each later call starts only after the previous result has arrived.
  2. Fulfills with the results in input order. At the first rejection, or throw, it rejects with it and calls fn for no later item.
  3. Works with any iterable, and fulfills with [] for an empty one.

Examples

JAVASCRIPT
const fetchPrice = (id) => new Promise((resolve) => setTimeout(() => resolve(id * 100), id === 1 ? 300 : 100));

await mapAsync([1, 2, 3], fetchPrice);  // [100, 200, 300] after 300 ms (all at once)
await mapSeries([1, 2, 3], fetchPrice); // [100, 200, 300] after 500 ms (300 + 100 + 100)
JAVASCRIPT
await mapAsync(new Set(["a", "b"]), (letter, index) => letter + index); // ["a0", "b1"]
JAVASCRIPT
await mapSeries([1, 2, 3], async (n) => {
  if (n === 2) throw new Error("stop at 2");
  return n;
});
// rejects with "stop at 2"; fn is never called with 3

Environment

  • Plain JavaScript in a browser page; the tests call the globals mapAsync and mapSeries from map-async.js.
  • The tests' mapper answers on a virtual clock (setTimeout), so no test waits for real time.
  • Promise.resolve, new Promise, then and async/await are allowed. A concurrency limit is problem 14.7.

Hints

  1. The results arrive in any order. Where does each one go, and how do you know the last one has come?
  2. resolve and reject can be called many times, but only the first call matters. How does that help with "the first rejection"?
  3. Which loop waits at each await, and which one does not?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…