Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
A practical guide to readable asynchronous JavaScript. You refactor a nested promise chain into async/await, learn when awaits run one after another and when they run in parallel, and build an async generator that pages through an API, with for await...of and early exit. The refactor and the generator were run with Node.js 22 against stubs and a local test server.

If you've written JavaScript for a while, you remember callbacks nested inside callbacks, the "pyramid of doom". Promises flattened it, but long .then() chains brought their own problems. This guide is for developers who use promises and want code that's easier to read. You'll refactor a nested promise chain into async/await, avoid running independent work one step at a time, and use async generators to page through an API.
This is part 12 of the Frontend & JavaScript Fundamentals series. It builds on the previous part, JavaScript promises.
Key takeaways
async/awaitdoesn't make code faster. It makes promise code read top to bottom, with ordinarytry/catch.- Awaiting independent calls one by one makes them run one after another. Start them together with
Promise.all. - An async generator yields items as they arrive.
for await...ofreads them, andbreakstops further fetching.
The mental model: async code that reads like sync code
An async function is a function that can pause at each await until a promise settles, then carry on with the result. MDN describes it as a way to write promise-based code in a cleaner style without building promise chains by hand.
The main benefit isn't speed. Underneath, it's still promises and the event loop. The benefit is that you can read the code in order, like synchronous code, while the waiting happens without blocking the page.
The problem: promise chains
Here's a realistic task. You need to:
- Fetch a user profile.
- Use the user id to fetch their recent posts.
- Enrich those posts with metadata from a different service.
With plain promises, it looks like this:
function getUserData(userId) {
return fetchUser(userId)
.then(user => {
return fetchPosts(user.id)
.then(posts => {
// Nested to keep access to 'user' scope
const enrichmentPromises = posts.map(post => enrichPost(post));
return Promise.all(enrichmentPromises)
.then(enrichedPosts => {
return { user, posts: enrichedPosts };
});
});
})
.catch(err => {
console.error("Data fetch failed", err);
throw err;
});
}
Why this hurts:
- Nesting: to keep
userin scope for the final object, you have to nest the second.then()inside the first. - Error handling: the single
.catch()is generic. It's hard to tell which step failed without a catch on every promise. - Reading order: the logic runs top to bottom, but the indentation makes you read it inside out.
The refactor: async/await
The same function with async/await is flatter. As a rule of thumb, this is the style to aim for in new code.
async function getUserData(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
// Parallel execution for enrichment
const enrichedPosts = await Promise.all(
posts.map(post => enrichPost(post))
);
return { user, posts: enrichedPosts };
} catch (error) {
// Ideally, you'd have custom error handling logic here
console.error(`Failed to fetch data for user ${userId}`, error);
throw error;
}
}
What improved:
- Flat scope:
userandpostslive in the same scope. No deep indentation. - Standard try/catch: MDN notes that
async/awaitlets you use ordinarytry/catcharound asynchronous code. - Intent: it reads top to bottom: get user, get posts, enrich, return.
fetchPosts waits for fetchUser on purpose, because it needs user.id. The enrichment calls don't depend on each other, so they run together.
A note on parallelism
A common mistake when switching to async/await is making independent work run one step at a time by accident.
Avoid this:
// Inside an async function, after posts is loaded
// Sequential: each await waits for the previous call to finish
for (const post of posts) {
await enrichPost(post);
}
If you have 10 posts and each takes 1 second, this loop takes about 10 seconds. Promise.all (as in the refactor) starts them all at once, so the total is close to the slowest single call, about 1 second here.
Do this instead:
// Inside an async function, after posts is loaded
// Concurrent: start every call, then wait for all of them
const enrichedPosts = await Promise.all(posts.map(post => enrichPost(post)));
Two details from MDN help here. Promise.all rejects as soon as any input rejects. If you need every result, including failures, use Promise.allSettled. And don't write [await p1, await p2] with promises you've already started. MDN marks that pattern "Do not do this!", because a rejection from p2 can go unhandled.
| Pattern | Runs | If one fails | Use when |
|---|---|---|---|
await in a for loop |
One after another | Stops at the failure | Each step needs the previous result, or the API has strict rate limits |
Promise.all |
All at once | Rejects with the first error | Calls are independent and you need every success |
Promise.allSettled |
All at once | Never rejects; reports each result | You want partial results and a list of what failed |
As a rule of thumb, for hundreds of calls to one API, run them in small batches instead of all at once, so you don't hit rate limits.
Generators: pause and resume
async/await is everywhere now. Generators are less well known. A generator function is a function that can be exited and later re-entered, with its variables saved in between, as MDN defines it. You write one with function*. Each yield hands out one value and pauses.
function* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const ids = idMaker();
console.log(ids.next().value); // 0
console.log(ids.next().value); // 1
An async generator (async function*) combines both features: MDN says you can use await and yield in the same body. That makes it a good fit for streams of data and paginated APIs.
The use case: pagination
Say an API returns data a page at a time, and you don't know how many pages there are. You want to loop over all items as if they were one array, without loading 10,000 items into memory at once.
This is where async function* helps.
/**
* A generator that yields items one by one from a paginated API
*/
async function* fetchAllItems(baseUrl) {
let nextUrl = baseUrl;
while (nextUrl) {
const response = await fetch(nextUrl);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
// Assume API returns { items: [], next: "url..." }
nextUrl = data.next;
// Yield individual items from the current page
for (const item of data.items) {
yield item;
}
}
}
The response.ok check is new in this version. MDN's fetch() reference explains that a 404 or 500 doesn't reject the promise, so without the check the generator would try to read an error page as data.
Consuming the generator
The consumer code stays short. A for await...of loop waits for each promise to resolve and for the generator to yield before it moves on.
async function processLargeDataset(url) {
// The generator handles the fetching internally.
// We just see a stream of users.
for await (const user of fetchAllItems(url)) {
await db.save(user);
if (shouldStopProcessing(user)) {
break; // Closes the generator: no more pages are fetched
}
}
}
Here db.save and shouldStopProcessing stand in for your own code. MDN's for await...of reference says an early break calls the iterator's return() method to clean up. For an async generator, that ends the function, so no further pages are requested.
Why generators matter for AI apps
When a chat app shows a model's answer word by word, it's reading a stream. Waiting for the whole response before showing anything feels slow. An async generator can yield each chunk as it arrives, and the UI can render it right away with for await...of.
Summary
Code that works is the baseline. Code that's easy to read and change is the goal.
- Refactor promise chains: as a rule of thumb, if a chain is nested more than two levels deep, rewrite it with
async/await. - Watch for waterfalls: don't await independent tasks one after another. Use
Promise.all, orPromise.allSettledwhen you need every result. - Reach for async generators: for streams, pagination or long sequences, they hide the paging state behind a simple loop.
Find the utility file in your project with the most nested promises, and clean it up. Then read the next part, inside the V8 engine, to see what runs this code.
Frequently asked questions
Is async/await faster than promises?
No. async/await is built on promises, so the work done is the same. The gain is readability and ordinary try/catch. Speed comes from running independent work in parallel, for example with Promise.all.
How do I run several awaits in parallel?
Start the promises first, then wait for all of them with await Promise.all([...]). Awaiting each call in turn makes them run one after another. Use Promise.allSettled if one failure shouldn't throw away the other results.
What is the difference between a generator and an async generator?
A generator (function*) yields values synchronously, and you read it with for...of or next(). An async generator is a generator declared with async function*. It can also await inside its body, and each next() returns a promise. You read it with for await...of.
What happens if I break out of a for await...of loop?
The loop calls the iterator's return() method to clean up, then exits. For an async generator, the function stops at that point. In the pagination example, that means no more pages are fetched.
Does Promise.all cancel the other requests when one fails?
No. Promise.all rejects with the first error, but the other promises keep running. To actually stop network requests, pass an AbortSignal to fetch and call abort().
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...