FrontendPro

42Implement asyncMap() preserving result order

mediumAbout 35 minutesCodingpromisesasyncarrays

Problem

Implement asyncMap(items, mapper). It calls the async mapper(item, index) for every item in parallel and returns a promise of the results in input order, however long each call takes.

const users = await asyncMap([3, 1, 2], async (id) => {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
});
// users[0] is user 3, even if user 1 arrived first

Requirements

  • Start every mapper call right away (do not wait for one before starting the next).
  • Results follow the input order, not completion order.
  • Reject as soon as any call rejects, with that reason.
  • If the mapper throws synchronously, reject instead of throwing.
  • Accept any iterable; an empty input resolves to [].

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

for (const item of items) results.push(await mapper(item)) is correct but sequential: ten 100 ms calls take a second. The task asks for parallel calls.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever