Lesson 32 of 34 · Async JavaScript
JavaScript async/await and Promise.all
Promise chains are a big improvement over nested callbacks, but .then(...).then(...).catch(...) still reads differently from normal code. async and await let you write asynchronous code that looks and reads like ordinary step-by-step code, while still never blocking the event loop.
Once you can await, the next question is speed: how do you run several tasks at the same time? That's what Promise.all is for.
async functions
Put async in front of a function and two things change:
- It always returns a promise. A returned value becomes the promise's result, and a thrown error rejects the promise.
- Inside it, you can use
await.
async function getAnswer() {
return 42;
}
getAnswer().then((value) => console.log(value)); // 42
await
await promise pauses the async function until the promise settles, then gives you its value. Only that function pauses: the rest of your program, including timers and the page itself, keeps running:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function brewPotion() {
console.log("Heating the cauldron...");
await wait(500);
console.log("Adding moonflower...");
await wait(500);
return "Potion of Night Vision";
}
brewPotion().then((potion) => console.log(potion));
Compare that to the equivalent .then() chain: same behaviour, much easier to read. await works with any promise, including the ones returned by fetch and other async functions. Normally await is only allowed inside async functions, but JavaScript modules (and this course's code editor) also allow it at the top level.
Error handling with try/catch
When an awaited promise rejects, await throws the error, so you handle it with the same try/catch you already know:
async function loadSave(loadFile) {
try {
const text = await loadFile();
return JSON.parse(text);
} catch (error) {
console.log(`Could not load: ${error.message}`);
return null;
}
}
Sequential versus parallel
Each await waits before the next line starts. That's right when step 2 needs step 1's result, but wasteful when tasks are independent:
// Sequential: about 3 seconds if each fetch takes 1 second
const a = await fetchHero(1);
const b = await fetchHero(2);
const c = await fetchHero(3);
To run independent tasks in parallel, start them all first and then wait for all of them with Promise.all:
// Parallel: about 1 second in total
const heroes = await Promise.all([fetchHero(1), fetchHero(2), fetchHero(3)]);
Promise.all takes an array of promises and returns one promise that resolves to an array of results, in the same order as the input, no matter which task finishes first. With map, it works for any number of tasks: await Promise.all(ids.map((id) => fetchHero(id))).
Promise.all is all-or-nothing: if any promise rejects, the whole thing rejects with that first error. When you want every outcome, successes and failures, use Promise.allSettled. It never rejects; it resolves to objects like { status: "fulfilled", value } or { status: "rejected", reason }.
Two more helpers: Promise.race settles as soon as the first promise settles, and Promise.any resolves with the first success.
Common mistakes
- Forgetting
await.const hero = fetchHero(1);gives you a promise, not the hero. awaitinsideforEach.forEachdoesn't wait for async callbacks. Usefor...offor sequential work, orPromise.allwithmapfor parallel work.- Awaiting independent tasks one by one. It works, but it's needlessly slow.
- Unhandled rejections. Every
awaitthat can fail needs atry/catchsomewhere up the call chain.
Assignment
All three functions receive an async "fetch" function as a parameter, so the tests can simulate a slow, unreliable server.
async function loadParty(ids, fetchHero)fetches every hero in parallel and resolves with an array of heroes in the same order asids. The tests check the timing: three fetches of 60 ms each must finish in well under 180 ms.async function loadPartySafe(ids, fetchHero)does the same, but heroes whose fetch fails are skipped instead of failing everything.async function fetchWithRetry(fetchFn, retries)callsfetchFn()and returns its result. If the call fails, it tries again, up toretriesextra times (retriesdefaults to2). If every attempt fails, it throws the last error.
const fetchHero = (id) =>
new Promise((resolve) => setTimeout(() => resolve({ id }), 60));
await loadParty([1, 2, 3], fetchHero); // [{ id: 1 }, { id: 2 }, { id: 3 }] after ~60 msPremium 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.
Async code and concurrency in other languages
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .