Async Patterns and Promise Combinators
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Choose between sequential and concurrent asynchronous work.
- Use Promise.all, allSettled, race and any correctly.
- Handle async errors and cancellation with async and await.
Overview
#From callbacks to async and await
Promises represent a future value and async functions return a promise, letting await pause inside the function without blocking the thread. Errors thrown in an async function become a rejected promise, so try and catch work as they do in synchronous code.
async function load(url) {
const res = await fetch(url);
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}
Combinators
Promise.all waits for every promise and rejects on the first failure. Promise.allSettled waits for all and reports each outcome, which is what you want when one failure should not discard the rest. Promise.race settles with the first result, and Promise.any settles with the first success and rejects only if all fail.
const [a, b] = await Promise.all([load('/a'), load('/b')]);
const results = await Promise.allSettled([load('/a'), load('/b')]);
Sequential versus concurrent
await inside a loop runs the operations one after another, which is correct when each depends on the previous result but slow when they are independent. Start independent promises together and await them as a group. Bound concurrency when the work is heavy, and cancel with AbortController when the result is no longer needed.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst results = await Promise.allSettled([ Promise.resolve(1), Promise.reject(new Error('x')) ]); console.log(results.map((r) => r.status).join(','));Exercise 2Explain
Explain the difference between awaiting inside a loop and starting the promises together.
starter.textfor (const url of urls) { await load(url); } await Promise.all(urls.map(load));Reveal the reference answer
reference.textAwaiting inside the loop runs each load only after the previous one finishes, so the total time is the sum of the durations. Starting them together with map and awaiting Promise.all runs them concurrently, so the total time is the longest single duration. The loop is correct when each step needs the previous result; the concurrent form is correct when the requests are independent.Authored expected output: sequential versus concurrent timing
The answer should connect the loop to sequential timing and the map with all to concurrent timing, and state when each is right.
Exercise 3Implement
Implement `mapLimit(items, limit, worker)` so it runs worker over the items with at most limit promises in flight at once.
starter.javascriptasync function mapLimit(items, limit, worker) { // your code here }Reveal the reference answer
reference.javascriptasync function mapLimit(items, limit, worker) { const results = new Array(items.length); let index = 0; async function run() { while (index < items.length) { const current = index++; results[current] = await worker(items[current], current); } } await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run)); return results; }Authored expected output: results in input order with bounded concurrency
A shared index lets each of the limit workers pull the next item until none remain. Storing by index keeps the output order stable regardless of completion order.
Exercise 4Debug
This function is meant to return the first successful result but rejects when the fastest promise fails. Find and fix the bug.
starter.javascriptasync function firstSuccess(urls) { return Promise.race(urls.map(load)); }Reveal the reference answer
reference.javascriptasync function firstSuccess(urls) { return Promise.any(urls.map(load)); }Authored expected output: the first fulfilled result
Promise.race settles with the first promise to settle, success or failure, so a fast rejection wins. Promise.any resolves with the first success and rejects only when all inputs reject.
Exercise 5Test
Write assertions that prove Promise.all rejects on the first failure while allSettled reports every outcome.
starter.javascriptfunction assertEqual(actual, expected, label) { if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value'); }Reveal the reference answer
reference.javascriptlet allFailed = false; try { await Promise.all([Promise.resolve(1), Promise.reject(new Error('x'))]); } catch { allFailed = true; } assertEqual(allFailed, true, 'Promise.all rejects on failure'); const settled = await Promise.allSettled([Promise.resolve(1), Promise.reject(new Error('x'))]); assertEqual(settled.map((r) => r.status), ['fulfilled', 'rejected'], 'allSettled reports each outcome'); console.log('all assertions passed');Authored expected output: all assertions passed
Promise.all short-circuits on the first rejection, so the try block catches. allSettled waits for all and returns a status for each input.
Exercise 6Interview
How would you fetch data for a dashboard with ten independent panels without overloading the server?
Reveal the reference answer
reference.textI would fire the independent requests concurrently but cap the number in flight with a small concurrency limit, and use Promise.allSettled so one failing panel does not blank the rest. I would cancel in-flight requests when the view unmounts with AbortController, cache responses where the data allows, and show per-panel loading and error states rather than one global spinner.The answer should name bounded concurrency, allSettled for partial failure, cancellation and per-panel states.
Common misconceptions
#- Promise.all resolves even when one input rejects.
- await blocks the whole thread.
- Starting promises in a loop and awaiting later is always safe.
Follow-up practice
#- javascript-foundations-fetch-and-network
- javascript-foundations-web-workers
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.