Lesson 34 of 34 · Async JavaScript
Async JavaScript Boss: The Storm Hydra
The Storm Hydra blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
The Storm Hydra rises from the Async Sea, and each of its heads answers on its own schedule: some strike back fast, some slowly, and some never at all. Strike every head at once, and never wait forever.
Battle plan
This final fight uses everything from the Async chapter, plus a custom error from Chapter 5:
- A custom error class,
TimeoutError, so callers can tell "too slow" apart from other failures withinstanceof. new PromiseandsetTimeoutto build a promise that rejects after a deadline.Promise.raceto let the real task and the deadline compete: whichever settles first decides the outcome.async/awaitandPromise.allSettledto strike all heads in parallel and collect every outcome, hits and misses alike.
The strike function is passed in as a parameter, just like the fetch functions in the last lesson. strike(head) returns a promise that resolves with the damage dealt (a number), or rejects if the head dodges.
Order matters in the result: missed must list the heads in the order they appear in heads, not the order in which they failed. Promise.allSettled keeps its results in input order, so the index of each result tells you which head it belongs to.
Assignment
class TimeoutError extends Error: the constructor takesms. The error'snameis"TimeoutError", itsmessageis"Timed out after <ms> ms", and it storesmsin a property calledms.withTimeout(promise, ms)returns a promise that settles likepromise(same value or same error) ifpromisesettles withinmsmilliseconds. Otherwise it rejects with aTimeoutErroraftermsmilliseconds, without waiting for the slow promise.async function strikeAll(heads, strike, ms)strikes all heads in parallel. Each strike isstrike(head), limited tomsmilliseconds withwithTimeout. Resolve with an object{ total, missed }:total: the sum of the damage of all successful strikes;missed: the names of the heads whose strike failed or timed out, in their original order.
// fire hits for 40, venom dodges, frost answers too late
await strikeAll(["fire", "venom", "frost"], strike, 100);
// { total: 40, missed: ["venom", "frost"] }Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .