call(back)
FrontendmediumSign in to star problems

mapAsync II

Implement mapAsyncLimit(items, fn, size = Infinity): map every item through an async function fn(item) that returns a promise, with at most size calls in flight, and resolve with the results. When a call settles, the next item starts right away.

Rules

  • Results come back in input order, whatever order the calls finish in.
  • items can be any iterable, not only an array. An empty input resolves to [].
  • Reject with the first rejection, and start no new calls after it. Calls already in flight may finish, but their results are ignored.
  • Use a sliding window, not fixed chunks. Awaiting Promise.all on one slice at a time makes every chunk wait for its slowest call, and the grader sees it in the start times.

Your helper runs on a virtual clock, and the grader's fn logs when each call starts and settles.

Hints

Hint 1

Start min(size, n) workers. Each loops: take the next index, await fn(items[i]), store the result at index i, repeat.

Hint 2

const i = next++ is safe without locks. JavaScript runs it synchronously between awaits, so two workers never take the same index.

Hint 3

Keep a failed flag. The worker whose call rejects sets it, and every worker checks it before taking another item.

Asked at