Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
12.7. Map over items with an async function
Medium
Topics
This question is in
12. Callbacks, promises and asyncitems.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
function mapAsync(items, fn) // returns a Promise of an array
function mapSeries(items, fn) // returns a Promise of an arrayitems: any iterable: an array, aSet, a generator.fn(item, index): returns a promise or a plain value.- Both fulfill with the results in input order.
Requirements
mapAsync:
- Returns a promise, and calls
fn(item, index)for every item during the call, without waiting for any result. - Fulfills when the last result arrives, with the results in input order, whatever order they finished in.
undefinedand falsy results keep their places. - Rejects with the first rejection as soon as it happens. If
fnthrows, the promise rejects with what it threw;mapAsyncitself does not throw. - Plain values from
fncount as results; an empty iterable fulfills with[]; holes in an array are passed tofnasundefined. Promise.all,Promise.allSettled,Promise.raceandPromise.anyare not used (the tests replace them).
mapSeries:
- Returns a promise and calls
fnfor the first item during the call. Each later call starts only after the previous result has arrived. - Fulfills with the results in input order. At the first rejection, or throw, it rejects with it and calls
fnfor no later item. - Works with any iterable, and fulfills with
[]for an empty one.
Examples
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)await mapAsync(new Set(["a", "b"]), (letter, index) => letter + index); // ["a0", "b1"]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 3Environment
- Plain JavaScript in a browser page; the tests call the globals
mapAsyncandmapSeriesfrommap-async.js. - The tests' mapper answers on a virtual clock (
setTimeout), so no test waits for real time. Promise.resolve,new Promise,thenandasync/awaitare allowed. A concurrency limit is problem 14.7.
Hints
- The results arrive in any order. Where does each one go, and how do you know the last one has come?
resolveandrejectcan be called many times, but only the first call matters. How does that help with "the first rejection"?- 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…